Binary Tree Preorder Traversal
Iterative stack — push right child first so left is processed next.
2 min read
tree dfs stack
Problem#
Given the root of a binary tree, return its preorder traversal (root, left, right) as a list.
Examples#
[1,null,2,3]→[1,2,3][]→[][1]→[1]
Constraints#
- The number of nodes is in
[0, 100].
Approach#
Iterative stack: pop, visit, push right first then left.
Solution#
class Solution {public: vector<int> preorderTraversal(TreeNode* root) { vector<int> ans; if (!root) return ans; stack<TreeNode*> st; st.push(root); while (!st.empty()) { TreeNode* u = st.top(); st.pop(); ans.push_back(u->val); if (u->right) st.push(u->right); if (u->left) st.push(u->left); } return ans; }};func preorderTraversal(root *TreeNode) []int { ans := []int{} if root == nil { return ans } stack := []*TreeNode{root} for len(stack) > 0 { u := stack[len(stack)-1] stack = stack[:len(stack)-1] ans = append(ans, u.Val) if u.Right != nil { stack = append(stack, u.Right) } if u.Left != nil { stack = append(stack, u.Left) } } return ans}from typing import List, Optional
class Solution: def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]: ans: List[int] = [] if not root: return ans stack = [root] while stack: u = stack.pop() ans.append(u.val) if u.right: stack.append(u.right) if u.left: stack.append(u.left) return ansvar preorderTraversal = function(root) { const ans = []; if (!root) return ans; const stack = [root]; while (stack.length > 0) { const u = stack.pop(); ans.push(u.val); if (u.right) stack.push(u.right); if (u.left) stack.push(u.left); } return ans;};class Solution { public List<Integer> preorderTraversal(TreeNode root) { List<Integer> ans = new ArrayList<>(); if (root == null) return ans; Deque<TreeNode> stack = new ArrayDeque<>(); stack.push(root); while (!stack.isEmpty()) { TreeNode u = stack.pop(); ans.add(u.val); if (u.right != null) stack.push(u.right); if (u.left != null) stack.push(u.left); } return ans; }}function preorderTraversal(root: TreeNode | null): number[] { const ans: number[] = []; if (!root) return ans; const stack: TreeNode[] = [root]; while (stack.length > 0) { const u = stack.pop()!; ans.push(u.val); if (u.right) stack.push(u.right); if (u.left) stack.push(u.left); } return ans;}Editorial#
The stack imposes a LIFO discipline, so pushing the right child first makes the left child the next to pop. Each node is pushed and popped once — linear total work.
Complexity#
- Time: O(n).
- Space: O(h).
Concept revision#
Related#