You are given an array nums of distinct numbers. Build a tree from it like this: the largest number becomes the root. The numbers to its left form the left subtree and the numbers to its right form the right subtree, each built by the same rule. A side with no numbers has no child.
Return the root of the finished tree.
Example 1
Input: nums = [4, 1, 7, 2, 5] Output: [7, 4, 5, null, 1, 2] Why: 7 is the root; [4, 1] builds the left side, [2, 5] the right
2 more examples and the constraints
Example 2
Input: nums = [3, 6, 9] Output: [9, 6, null, 3] Why: each largest number has everything else to its left
Example 3
Input: nums = [8] Output: [8] Why: one number is the whole tree
Constraints
- 1 ≤ length of nums ≤ 1,000
- 0 ≤ nums[i] ≤ 1,000
- All the numbers are different
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Recursion: find the max, splitO(n²)
- Monotonic 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 1,000 sorted numbers | Verdict |
|---|---|---|---|
| Recursion | O(n²) | Passes; slow on sorted input | |
| Monotonic stack | O(n) | Best; one pass |
n = length of nums. The output is the tree in level order, with null for a missing child.
Edge cases to test
- One number. [8] is a single node.
- Increasing input. [3, 6, 9] gives a chain of left children.
- Decreasing input. [5, 4, 3, 2, 1] gives a chain of right children; nothing is ever popped.
- Largest at an end. One side of the root is empty.
Common mistakes
- Making the first popped node the left child instead of the last one popped.
- Forgetting to update the right child of the node on top, so later numbers are lost.
- Returning the top of the stack instead of the bottom.
How to talk through it
- 1Clarify. Are the numbers distinct? Is the output the tree’s root?
- 2Give the recursion. Find the max, split, recurse; say sorted input makes it O(n²).
- 3Name the structure. A node’s parent is the smaller of its nearest bigger neighbours, which a decreasing stack finds.
- 4Code the stack. Pop smaller nodes into the left child, attach to the top as a right child, push.
- 5Test out loud. Run an increasing and a decreasing array.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?