Binary Tree Preorder Traversal
Easy
Topics
Given the root of a binary tree, return its preorder traversal (node, left, right) as a list of values.
Example 1
visited first
The small number above each node is its position in the output: node, left subtree, right subtree, giving
[1, 2, 3]. The node is emitted before either subtree, which is why this order can rebuild the tree from scratch. The iterative version swaps the call stack for an explicit one.Tree given in level-order (breadth-first);
null marks a missing child.Input: root = [1,null,2,3] Output: [1,2,3]
Example 2
visited first
Input: root = [1,2,3,4,5] Output: [1,2,4,5,3]
Constraints
- 0 <= number of nodes <= 100
- -100 <= Node.val <= 100
Editorial — intuition, approach, complexity and pitfalls
Intuition
Preorder visits the node before its subtrees: node, then left, then right.
Approach
- Append the current node’s value.
- Recurse left, then recurse right.
Dry Run
1
/ \
2 3
/ \
4 5
Preorder appends before descending anywhere:
at 1: VISIT res 1
descend left
at 2: VISIT res 1 2
descend left
at 4: VISIT res 1 2 4
both children null
descend right
at 5: VISIT res 1 2 4 5
both children null
descend right
at 3: VISIT res 1 2 4 5 3
both children null
answer 1 2 4 5 3
The root arrives first and each node arrives before anything beneath it. That is
why preorder is the traversal you serialise with: a reader rebuilding the tree
always has the parent in hand before its children show up, so it can attach them
without buffering.
The descent is the same for all three traversals; only where res.append sits
changes the output:
preorder 1 2 4 5 3 append before descending
inorder 4 2 5 1 3 append between the two descents
postorder 4 5 2 3 1 append after both descents
Note the left subtree is finished entirely before the right begins -- 2, 4 and 5
all land before 3, even though 3 is shallower than 4 and 5. Preorder is depth
first, not level by level.Complexity
- Time — O(n): each node visited once.
- Space — O(h): stack up to height h.
Common Pitfalls
- The visit comes first, before either recursive call. Moving it after both gives postorder:
4 5 2 3 1where preorder is1 2 4 5 3. - Preorder is the one that serialises a tree you can rebuild, because the root arrives before anything that depends on knowing it.
Full Solution — all languages
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def preorderTraversal(self, root):
res = []
def dfs(node):
if not node:
return
res.append(node.val)
dfs(node.left)
dfs(node.right)
dfs(root)
return resimport java.util.*;
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int v) {
val = v;
}
}
class Solution {
public int[] preorderTraversal(TreeNode root) {
List<Integer> res = new ArrayList<>();
Deque<TreeNode> st = new ArrayDeque<>();
if (root != null) st.push(root);
while (!st.isEmpty()) {
TreeNode n = st.pop();
res.add(n.val);
if (n.right != null) st.push(n.right);
if (n.left != null) st.push(n.left);
}
int[] a = new int[res.size()];
for (int i = 0; i < a.length; i++) a[i] = res.get(i);
return a;
}
}#include <bits/stdc++.h>
using namespace std;
struct TreeNode {
int val;
TreeNode *left, *right;
TreeNode(int v): val(v), left(nullptr), right(nullptr) {
}
};
class Solution {
public: vector<int> preorderTraversal(TreeNode* root) {
vector<int> res;
function<void(TreeNode*)> dfs = [&](TreeNode* node) {
if (!node) return;
res.push_back(node->val);
dfs(node->left);
dfs(node->right);
};
dfs(root);
return res;
}
};/**
* Tree node shape: { val, left, right }
* @param {TreeNode} root
* @return {number[]}
*/ var preorderTraversal = function(root) {
const res = [];
const dfs = node => {
if (!node) return;
res.push(node.val);
dfs(node.left);
dfs(node.right);
};
dfs(root);
return res;
};