Deep trees need your own stack
transcript
Your recursive tree code passes every example. Then the judge sends a long chain. A hundred thousand nodes deep. Crash.
Every recursive call uses the call stack. A chain needs one call for every level. Too deep, and the call stack overflows.
Keep your own stack instead. It lives in ordinary memory, not the call stack. A hundred thousand nodes fit easily. There is no depth limit to hit.
Push the root, node five. Pop five. Push eight, then three. Pop three, then one, then four. Then eight and nine.
Push the right child first. A stack pops the last item pushed. So the left child pops first. You get the same order as recursion.
Need the rows of the tree instead? Swap the stack for a queue. Still no recursion, and still no limit.
Deep trees need your own stack. Push right, then left. Full breakdown in the lecture.