Binary Tree Preorder Traversal

Iterative stack — push right child first so left is processed next.

Easy
Time O(n) Space O(h)
LeetCode
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#

Binary Tree Preorder Traversal
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;
}
};

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#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.