Given a whole number n, build every binary search tree whose nodes hold exactly the values 1 to n, each value once. Two trees count as different when their shapes differ, or when the same position holds a different value.
Return the roots of all those trees, in any order. Each tree is shown as its level-order list, with null for a missing child.
Example 1
Input: n = 2 Output: [[1,null,2],[2,1]] Why: the root is 1 with 2 to its right, or 2 with 1 to its left
2 more examples and the constraints
Example 2
Input: n = 1 Output: [[1]] Why: a single node is the only tree
Example 3
Input: n = 4 Output: 14 trees, from [1,null,2,null,3,null,4] to [4,3,null,2,null,1] Why: 1, 1, 2, 5, 14: each root splits the rest into two smaller sets
Constraints
- 1 ≤ n ≤ 8
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Build every rangeO(n · Cₙ)
- Memo by rangeO(Cₙ)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for n = 8 | Verdict |
|---|---|---|---|
| Build every range | O(n · Cₙ) | Passes; simple to explain | |
| Memo by range | O(Cₙ) | Best; each range built once |
n = the largest value; Cₙ = the n-th Catalan number, the number of trees (1,430 at n = 8).
Edge cases to test
- n = 1. One tree, a single node: [[1]].
- Empty side. When the root is the smallest or largest value, one side is empty. Return [None] for an empty range, not [], or the loops pair nothing.
- n = 8. 1,430 trees: still small, but every tree must really be built.
- Shared subtrees. With the memo, many trees point at the same node objects. Fine for reading; copy if the caller will edit.
Common mistakes
- Returning an empty list for an empty range, so roots 1 and n produce no trees at all.
- Building the right list inside the left loop, so it is rebuilt once per left tree.
- Reusing one node object for the root across trees, so changing one tree changes another.
How to talk through it
- 1Clarify. Values 1 to n, each once? Do we return the roots, in any order? May trees share subtrees?
- 2Use the BST rule. Choosing the root splits the values: smaller ones left, larger ones right.
- 3Write the recursion. build(lo, hi) tries every root and pairs every left tree with every right tree.
- 4Add the memo. The same ranges come back; store each one by (lo, hi) and share the subtrees.
- 5Test out loud. Check n = 1 gives one tree and n = 3 gives five.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?