Walk a deep tree without recursion
transcript
A tree can be one long chain. Recursion needs one frame per level. Python stops at a thousand calls. Fifteen hundred nodes already fail.
Keep the waiting work in a stack of your own. It lives on the heap. Each step pops one piece of work. Then it pushes the pieces that the pop creates.
An inorder walk pushes the left path first. The deepest node pops first and prints seven. Then nine, then its right child, one. Then four, two and eight. Seven, nine, one, four, two, eight.
A chain of a hundred thousand nodes fills it. A complete tree of the same size needs only seventeen. Memory follows the height, not the count.
In preorder, pop a node and visit it. Push the right child first. Then push the left. It pops first.
Keep the work still owed on a stack. Test a chain of a hundred thousand. Full breakdown in the lecture.