EasyTreesAI interview only
Binary Tree Preorder Traversal
Asked atmicrosoftamazongooglebloombergapple
01 · Problem
Given the root of a binary tree, return a list of its node values in preorder (node, then left subtree, then right subtree) order.
The tree is given in level-order, with null marking a missing child. Return an empty list for an empty tree.
02 · Examples
Example 01
1
\
2
/
3Input
root = [1,null,2,3]
Output
[1,2,3]
Node 1 has right child 2, and 2 has left child 3. Visiting node, left, right gives [1,2,3].
Example 02
1
/ \
2 3
/ \ \
4 5 8
/ \ /
6 7 9Input
root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output
[1,2,4,5,6,7,3,8,9]
Applying the preorder (node, then left subtree, then right subtree) rule recursively at every node gives [1,2,4,5,6,7,3,8,9].
Example 03
Input
root = []
Output
[]
An empty tree produces an empty list.
03 · Constraints
- 01The number of nodes in the tree is in the range [0, 100].
- 02-100 <= Node.val <= 100
- 03Node values are not necessarily unique.
- 04The tree height is at most 100, and the tree may be fully skewed.
04 · Optimal complexity
- Time
- O(n)
- Space
- O(h)
05 · Two ways to work on it
Practice it alone or rehearse it as an interview.
Practice Mode gives you an editor and test runs, nothing else. AI Interview Mode puts a voice interviewer on the other side, adds a clock, and ends with a scored summary of the round.