Skip to problem
←

Unique Binary Search Trees II

Medium 0 attempts

Construct every structurally distinct binary search tree using each key from 1 through n exactly once.

For every node, all values in its left subtree must be smaller and all values in its right subtree must be larger. Left and right positions are distinct. Different insertion sequences that create the same structure count as one tree.

Return an array of tree-root objects, not serialized arrays. Each node has val, left, and right properties; a missing child is null. The displayed examples use level-order arrays only to show those objects compactly.

Return all valid trees exactly once, in any order. For n = 2, the two possibilities are root 1 with right child 2, and root 2 with left child 1.

Function contract

Implement generateTrees(n).

Output: Return an array of tree roots with val, left, and right properties. Use null for missing children. The runner displays each tree as a level-order array; tree order is ignored, but duplicate or missing trees are incorrect.

Example 1

Input
n = 2
Output
[[1,null,2],[2,1]]

Example 2

Input
n = 1
Output
[[1]]
Constraints
  • 1 <= n <= 8

Recursive Generation

Choose each possible root in the interval. Recursively generate every left tree from smaller keys and every right tree from larger keys, then combine every left/right pair with that root. Different roots or child shapes produce different trees.

An empty interval returns [null], representing one choice of an absent child. Returning an empty array there would incorrectly eliminate combinations with a missing child.

javascript
function generateTrees(n) {
  function build(lo, hi) {
    if (lo > hi) return [null];
    const trees = [];
    for (let i = lo; i <= hi; i++) {
      for (const left of build(lo, i-1)) {
        for (const right of build(i+1, hi)) {
          trees.push({val: i, left, right});
        }
      }
    }
    return trees;
  }
  return n === 0 ? [] : build(1, n);
}

Time: O(n × Cn) as a loose upper bound, where Cn is the nth Catalan number | Space: O(n × Cn), including returned trees

Loading discussion…

Saved in this browser only. Private to you.

JavaScript