Binary Tree Preorder Traversal – Solution & Complexity
Solution Walkthrough
Step 1: Recognize the preorder pattern
Preorder traversal always does the same three actions at every node: record the current node, traverse the left subtree, then traverse the right subtree. That makes this a standard depth-first search problem with a deterministic visit order.
Step 2: Recursive DFS solution
Use a helper DFS that stops on
None, appends the current node's value first, then recursively processes the left child and the right child. This matches the definition of preorder traversal directly.Step 3: Iterative stack solution and complexity
Time: O(n) because each node is visited exactly once. Space: O(h) for the explicit stack, where
his the tree height (O(n)in the worst skewed case). This stack-based preorder traversal is an optimal approach that avoids recursion depth concerns: pop a node, record it, then push its right child before its left child so the left subtree is processed first.