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 INPUT Binary Tree Structure 1 2 3 Input Array Representation: root = [1, null, 2, 3] ALGORITHM STEPS 1 Visit Root Process current node (1) 2 Traverse Left Left is null, skip 3 Traverse Right Go to node 2 4 Recurse Visit 2, then left (3) Traversal Order: 1 Root --> 2 Right --> 3 Left FINAL RESULT Visit Order Marked 1 1st 2 2nd 3 3rd Output: [1, 2, 3] OK - Preorder Complete! Key Insight: Preorder traversal follows Root-Left-Right pattern. Use recursion or a stack for iterative approach. Time Complexity: O(n) where n is number of nodes. Space Complexity: O(h) where h is tree height. TutorialsPoint - Binary Tree Preorder Traversal | Optimal Solution
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