Binary Tree Preorder Traversal (LeetCode 144): Solution and Explanation
Given the root of a binary tree, return its values in preorder: each node first, then its left subtree, then its right subtree. The tree has up to 100 nodes and may be empty. The recursive answer is short, so the interesting part is doing it with an explicit stack.
Intuition
Preorder visits a node the moment it is reached, before looking at anything below it. That makes it the simplest depth-first order to run with a stack: whatever is on top of the stack is the next node to visit.
After visiting a node, both children still need visiting, left subtree first. A stack is last in, first out, so the child pushed last is popped first. Push the right child, then the left child, and the left one comes off next.
The right child waits underneath while the entire left subtree is processed above it. Once that subtree is used up, the right child surfaces on top, exactly when preorder wants it.
Approach: Iterative DFS with a stack
- If the root is null, return an empty list.
- Push the root onto a stack.
- While the stack is not empty, pop a node and append its value to res.
- If it has a right child, push it.
- If it has a left child, push it, so it is on top.
- Return res when the stack is empty.
Step-by-step example
root = [1,2,3,4,5,null,8,null,null,6,7,9]
- Stack [1]. Pop 1, res = [1]. Push 3, then 2. Stack [3,2].
- Pop 2, res = [1,2]. Push 5, then 4. Stack [3,5,4].
- Pop 4, a leaf, res = [1,2,4]. Stack [3,5].
- Pop 5, res = [1,2,4,5]. Push 7, then 6. Pop 6 and then 7, both leaves: res = [1,2,4,5,6,7]. Stack [3].
- Pop 3, res gets 3. It has only a right child, so push 8. Pop 8 and push its left child 9. Pop 9.
- The stack is empty. Return [1,2,4,5,6,7,3,8,9].
Code: Python, Java, C++
1class Solution:
2 def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
3 if not root:
4 return []
5 res = []
6 stack = [root]
7 while stack:
8 node = stack.pop()
9 res.append(node.val)
10 if node.right:
11 stack.append(node.right)
12 if node.left:
13 stack.append(node.left)
14 return res1class Solution {
2 public List<Integer> preorderTraversal(TreeNode root) {
3 List<Integer> res = new ArrayList<>();
4 if (root == null) return res;
5 Deque<TreeNode> stack = new ArrayDeque<>();
6 stack.push(root);
7 while (!stack.isEmpty()) {
8 TreeNode node = stack.pop();
9 res.add(node.val);
10 if (node.right != null) stack.push(node.right);
11 if (node.left != null) stack.push(node.left);
12 }
13 return res;
14 }
15}1class Solution {
2public:
3 vector<int> preorderTraversal(TreeNode* root) {
4 vector<int> res;
5 if (!root) return res;
6 stack<TreeNode*> st;
7 st.push(root);
8 while (!st.empty()) {
9 TreeNode* node = st.top();
10 st.pop();
11 res.push_back(node->val);
12 if (node->right) st.push(node->right);
13 if (node->left) st.push(node->left);
14 }
15 return res;
16 }
17};Time and space complexity
O(n)
Every node is pushed once and popped once.
O(n)
The stack holds at most one pending right child per level of the current path plus the current node's children, so O(h), which is O(n) for a skewed tree. The output itself is O(n).
Other approaches
Recursion (time O(n), space O(h))
Append the node's value, recurse on the left child, recurse on the right child. The call stack plays the role of the explicit stack.
Morris traversal (time O(n), space O(1))
Threads each node's inorder predecessor back to it so the walk can return without a stack, recording a node the first time it is reached. Restores the tree as it goes.
Stack of right children only (time O(n), space O(h))
Walk left from the current node, visiting each node on the way and pushing its right child. When the left path ends, pop the next right child and continue from there.
Common mistakes
- Pushing the left child before the right child. The stack then pops the right subtree first and the order comes out wrong.
- Pushing null children. Either skip them, or check for null after popping; mixing the two leads to null dereferences.
- Forgetting the empty tree. Pushing a null root and then reading its value fails immediately.
- Using a queue instead of a stack. That gives level order, not preorder.
Frequently asked questions
How is this different from inorder and postorder?
Only in when the node itself is recorded. Preorder records it before both subtrees, inorder between them, and postorder after them. Preorder is the easiest to do iteratively because the node is recorded the moment it is popped.
Why not just use recursion?
Recursion is fine for 100 nodes. The iterative version is what interviewers usually ask for as the follow-up, and it avoids stack overflow on very deep trees.
What is preorder used for?
Copying or serializing a tree. Writing nodes in preorder with markers for nulls lets you rebuild the exact same tree, because each node appears before its children.