You are given the root of a tree in which a node can have any number of children, kept in order from left to right. Return the values of all nodes in preorder: a node first, then the whole subtree of its first child, then the whole subtree of its second child, and so on.
In the examples, a tree is written level by level. The root comes first, then a null, then each node's children as a group, with a null closing every group.
Example 1
Input: root = [4, null, 6, 1, 8, null, 2, 5, null, null, 3] Output: [4, 6, 2, 5, 1, 8, 3] Why: 4, then 6 with its children 2 and 5, then 1, then 8 with 3
2 more examples and the constraints
Example 2
Input: root = [] Output: [] Why: an empty tree has nothing to list
Example 3
Input: root = [9, null, 7, null, 0] Output: [9, 7, 0] Why: a chain is listed top to bottom
Constraints
- 0 ≤ number of nodes ≤ 10,000
- 0 ≤ node value ≤ 10,000
- The tree is at most 1,000 levels deep
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- RecursionO(n)
- Explicit stackO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 10,000 nodes | Verdict |
|---|---|---|---|
| Recursion | O(n) | Shortest; uses the call stack | |
| Explicit stack | O(n) | Best; no recursion depth to worry about |
n = number of nodes, h = height of the tree. Both do the same work; they differ in where the waiting nodes are kept.
Edge cases to test
- Empty tree.
rootis null: return an empty list, and do not push null onto the stack. - One node. [5] gives [5].
- A long chain. 1,000 levels with one child each: recursion goes 1,000 calls deep; the stack never holds more than one node.
- A wide root. A root with thousands of children: the stack holds all of them at once, recursion only one frame.
- Repeated values. Values need not be unique; list them as they are.
Common mistakes
- Pushing the children left to right, which lists the rightmost subtree first.
- Pushing null for an empty tree and then reading its value.
- Visiting all children before going deeper, which is level order, not preorder.
How to talk through it
- 1Clarify. Can the tree be empty? Are the children ordered? Do you want recursion or an iterative answer?
- 2Give the recursion. Write the node, then recurse into each child. O(n) time, O(h) call stack.
- 3Swap in a stack. Pop, write, push the children. Point out that the stack is last in, first out.
- 4Explain the reverse. Children go on in reverse so the leftmost comes off first.
- 5Test out loud. Run the empty tree, a single node and Example 1 before saying you are done.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?