Binary Tree Preorder Traversal Problem
Description
LeetCode Problem 144.
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
Example 5:
Input: root = [1,null,2]
Output: [1,2]
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
Solution
Approach: Iterative DFS with a Stack
Preorder visits a node first, then its whole left subtree, then its whole right subtree. The recursive version is three lines; the iterative version does the same work with an explicit stack instead of the call stack, which is what interviewers usually ask for.
- Push
rootonto the stack (if the tree is not empty). - While the stack is not empty, pop a node and append its value to the result.
- Push its right child, then its left child (skipping missing children).
The order in step 3 is the detail to get right. A stack is last in, first out, so the child pushed last is popped next. Pushing the left child last means the entire left subtree is visited before the right child comes back off the stack.
For root = [1, null, 2, 3]: pop 1 (push 2), pop 2 (push its left child 3), pop 3. The result is [1, 2, 3].
Complexity: O(n) time, where n is the number of nodes, since each node is pushed and popped once. O(h) extra space for the stack, where h is the height of the tree (O(n) in the worst case).
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
result = []
stack = [root] if root else []
while stack:
node = stack.pop()
result.append(node.val) # visit the node before its children
# Push the right child first, so the left child is popped (visited) first.
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result