Binary Tree Preorder Traversal (Recursive)
Binary Tree Preorder Traversal (Recursive) is a easy trees & bst problem solved with the recursion pattern.
The best approach, iterative (stack), runs in O(n) time and O(h) space.
Below are 2 approaches in Java, Python, C++ and JavaScript, from recursive dfs up.
Problem
Return the preorder traversal (node, left, right) of a binary tree.
Examples
Example 1
- Input
root = [4, 2, 6, 1, 3]- Output
[4, 2, 1, 3, 6]
Example 2
- Input
root = [1, null, 2]- Output
[1, 2]
Constraints
- The tree has
0to100nodes.
Solve it here
Write your solution in Java, Python, C++ or JavaScript and run it against the examples, right in the page. Submit runs the hidden tests too and, with a free account, records the solve in your revision log.
Your own testcases: Run checks these, and the expected output comes from our reference solution.
My submissions
Nothing yet. Every Run and Submit you make while signed in shows up here.
| When | Result | Tests | Runtime | Your time | Type |
|---|
Run checks the testcases above (2 examples, or your own). Submit also runs 12 hidden tests and saves the solve to your log. Signed in, every Run and Submit is saved under My submissions; your draft stays in this browser.
Animated walkthrough
A narrated, step-by-step animation that builds the solution from the idea up. Press play, or step through it at your own pace.
Concepts first, then the problem and every approach, step by step.
Space to play or pause · ← → to jump a step · click or drag the bar to seek
Solutions
Try it yourself first. Then compare: each approach lists its idea, the steps, its time and space, and the code in Java, Python, C++ and JavaScript.
| Approach | Time | Space |
|---|---|---|
| Recursive DFS | O(n) | O(h) |
| Iterative (stack) | O(n) | O(h) |
1Recursive DFS
O(n)O(h)Record the node before visiting its children.
- if node == null return.
- add(node.val); preorder(left); preorder(right).
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
preorder(root, out);
return out;
}
private void preorder(TreeNode node, List<Integer> out) {
if (node == null) return;
out.add(node.val);
preorder(node.left, out);
preorder(node.right, out);
}
}class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out: List[int] = []
self.preorder(root, out)
return out
def preorder(self, node: Optional[TreeNode], out: List[int]) -> None:
if node is None:
return
out.append(node.val)
self.preorder(node.left, out)
self.preorder(node.right, out)class Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> out;
preorder(root, out);
return out;
}
private:
void preorder(TreeNode* node, vector<int>& out) {
if (node == nullptr) return;
out.push_back(node->val);
preorder(node->left, out);
preorder(node->right, out);
}
};function preorderTraversal(root) {
const out = [];
preorder(root, out);
return out;
}
function preorder(node, out) {
if (node === null) return;
out.push(node.val);
preorder(node.left, out);
preorder(node.right, out);
}2Iterative (stack)
O(n)O(h)Pop a node, record it, then push its right child before its left so the left is processed first.
- Push root; while the stack is not empty: pop, add, push right, push left.
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> out = new ArrayList<>();
if (root == null) return out;
Deque<TreeNode> st = new ArrayDeque<>();
st.push(root);
while (!st.isEmpty()) {
TreeNode n = st.pop();
out.add(n.val);
if (n.right != null) st.push(n.right);
if (n.left != null) st.push(n.left);
}
return out;
}
}class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
out: List[int] = []
if root is None:
return out
st = [root]
while st:
n = st.pop()
out.append(n.val)
if n.right is not None:
st.append(n.right)
if n.left is not None:
st.append(n.left)
return outclass Solution {
public:
vector<int> preorderTraversal(TreeNode* root) {
vector<int> out;
if (root == nullptr) return out;
stack<TreeNode*> st;
st.push(root);
while (!st.empty()) {
TreeNode* n = st.top(); st.pop();
out.push_back(n->val);
if (n->right != nullptr) st.push(n->right);
if (n->left != nullptr) st.push(n->left);
}
return out;
}
};function preorderTraversal(root) {
const out = [];
if (root === null) return out;
const st = [root];
while (st.length > 0) {
const n = st.pop();
out.push(n.val);
if (n.right !== null) st.push(n.right);
if (n.left !== null) st.push(n.left);
}
return out;
}Edge cases to test
- Empty tree
Hints
Hint 1
Preorder = root first, then left, then right. It is the order used to copy or serialize a tree.
FAQ
What is the best time complexity for Binary Tree Preorder Traversal (Recursive)?
Iterative (stack) runs in O(n) time and O(h) extra space.
Which pattern does Binary Tree Preorder Traversal (Recursive) use?
It is a trees & bst problem that uses the recursion pattern. Other problems with the same pattern: Binary Tree Inorder Traversal (Recursive), Binary Tree Postorder Traversal (Recursive), Binary Tree Inorder Traversal (Iterative).
Is there a brute force solution for Binary Tree Preorder Traversal (Recursive)?
Yes. Recursive DFS takes O(n) time and O(h) space. Record the node before visiting its children.
Which edge cases should I test for Binary Tree Preorder Traversal (Recursive)?
Empty tree.