Binary Tree Preorder Traversal - Problem
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Preorder traversal follows the pattern: Root โ Left โ Right. This means we visit the current node first, then recursively traverse the left subtree, followed by the right subtree.
For example, in a tree with root value 1, left child 2, and right child 3, the preorder traversal would be [1, 2, 3].
Note: You may implement this using recursion or iteration. Both approaches are valuable to understand!
Input & Output
example_1.py โ Basic Tree
$
Input:
root = [1, null, 2, 3]
โบ
Output:
[1, 2, 3]
๐ก Note:
Start at root (1), no left child so go to right child (2). At node 2, visit left child (3) first, then right (null). Final order: 1 โ 2 โ 3
example_2.py โ Empty Tree
$
Input:
root = []
โบ
Output:
[]
๐ก Note:
An empty tree has no nodes to traverse, so return an empty list
example_3.py โ Single Node
$
Input:
root = [1]
โบ
Output:
[1]
๐ก Note:
Tree with only root node returns just that single value
Visualization
Tap to expand
Understanding the Visualization
1
Visit Current Node
Process/record the current node's value immediately upon arrival
2
Explore Left Branch
Recursively traverse the entire left subtree before moving right
3
Explore Right Branch
After completing left subtree, recursively traverse the right subtree
4
Backtrack
Return to parent node and continue with its remaining subtrees
Key Takeaway
๐ฏ Key Insight: Preorder traversal naturally follows a "process first, then recurse" pattern, making it perfect for operations like copying trees or prefix expression evaluation.
Time & Space Complexity
Time Complexity
O(n)
We visit each node exactly once, where n is the number of nodes
โ Linear Growth
Space Complexity
O(h)
Stack space proportional to tree height h, which is O(log n) for balanced trees, O(n) for skewed trees
โ Linear Space
Constraints
-
The number of nodes in the tree is in the range
[0, 100] -
-100 โค Node.val โค 100 - Follow up: Recursive solution is trivial, could you do it iteratively?
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code