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

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?

Visualization

Tap to expand
12345Traversal Order:โ‘  Node 1 (root)โ‘ก Node 2 (left subtree root)โ‘ข Node 4 (leftmost leaf)โ‘ฃ Node 5 (right of node 2)โ‘ค Node 3 (right subtree)Preorder: Root โ†’ Left โ†’ Right
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 25
52.0K Views
High Frequency
~15 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen