Binary Tree Inorder Traversal – Solution & Complexity
Solution Walkthrough
Step 1: Recognize the traversal order
In-order traversal always follows the same pattern at every node: visit the left subtree, then record the current node, then visit the right subtree. That makes this a straightforward depth-first search problem.
Step 2: Recursive DFS solution
Use a helper DFS that stops on
None, recursively processes the left child, appends the current value, and then processes the right child. This mirrors the definition of in-order traversal directly.Step 3: Think through edge cases
An empty tree should return
[]. A single node should return just that value. Skewed trees should still work because the traversal naturally unwinds back up the call stack in the correct left-node-right order.Step 4: Iterative stack solution and complexity
Time: O(n) because each node is pushed and popped at most once. Space: O(h) for the stack, where
his the tree height (O(n)worst case on a skewed tree). The iterative version simulates the recursive call stack explicitly: keep walking left, pop the next node to visit, record it, then move to its right subtree.