Binary Tree Preorder Traversal - Problem
Given the root of a binary tree, return the preorder traversal of its nodes' values.
In preorder traversal, we visit nodes in the following order:
- Root node first
- Left subtree
- Right subtree
For example, given a tree with root 1, left child 2, and right child 3, the preorder traversal would be [1, 2, 3].
Input & Output
Example 1 — Basic Tree
$
Input:
root = [1,null,2,3]
›
Output:
[1,2,3]
💡 Note:
Visit root 1 first, then right subtree. In right subtree: visit 2, then its left child 3. Final order: 1 → 2 → 3
Example 2 — Empty Tree
$
Input:
root = []
›
Output:
[]
💡 Note:
Empty tree has no nodes, so preorder traversal returns empty array
Example 3 — Single Node
$
Input:
root = [1]
›
Output:
[1]
💡 Note:
Tree with only root node returns array with just that value
Constraints
- The number of nodes in the tree is in the range [0, 100]
- -100 ≤ Node.val ≤ 100
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with nodes containing integer values
2
Preorder Visit
Visit root first, then left subtree, then right subtree
3
Output Array
Array of values in preorder sequence
Key Takeaway
🎯 Key Insight: Preorder means process current node before exploring children
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code