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:

  1. Root node first
  2. Left subtree
  3. 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
Binary Tree Preorder Traversal: Root → Left → Right123[1, 2, 3]Input: Tree structureOutput: Preorder array
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
Asked in
Google 45 Amazon 38 Microsoft 32 Apple 28
89.2K Views
High Frequency
~15 min Avg. Time
2.8K 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