Given the root of a tree root
, return the inorder traversal of the tree in the form of an array.
Here's our original solution to this problem that uses recursive code - try converting this code into iterative code.
This is one of our favorite problems. You learn a lot about the Call Stack through this problem.
This iterative solution is harder because we want to pick up where we left off after calling visitAll(node.left)
. Preorder was easy was because it called both recursive functions last, so it never had to pick up where it left off.
The trick to doing this is to visit each node twice. The first time you visit a node, you should not act on the node, and should instead first run visitAll on the node's left child, and then come back. When you come back to a node for the second time, you're ready to operate on the node now (add it to the traversal). Here's the code for this:
Time Complexity O(n)
Space Complexity O(n). The stack
takes up as much space as the Call Stack would have if we wrote this recursively, since the stack is just our own version of the Call Stack. This means stack
can get n calls deep, requiring O(n) space.