Unique Binary Search Trees II solution explained

To list every binary search tree that holds the keys 1 to n, recurse on the root: for each key r in a range, build all left subtrees from the keys below r and all right subtrees from the keys above r, and attach every left to every right under a new node r. The output has Catalan(n) trees, so the work is roughly O(n · Catalan(n)) whatever you do; memoizing ranges lets trees share subtrees and cuts the repeated building.

By Published 8 min read

What the problem wants

Given n, produce a list of root nodes, one for each binary search tree whose nodes carry exactly the values 1 to n. Two trees belong in the list only if their shapes differ. The order of the list does not matter. A preorder list of values is enough to identify a BST, because the sorted order fixes the inorder, which is how the table below writes them. This is the generating version of Unique Binary Search Trees, which only asks how many such trees exist, and that count tells you the size of the output before you write any code.

Small cases, each tree written as its preorder list of values
nTreesThe trees in preorder
111
221 2, and 2 1
351 2 3, 1 3 2, 2 1 3, 3 1 2, 3 2 1
414Root 1: 5 trees, root 2: 2, root 3: 2, root 4: 5
Small cases, each tree written as its preorder list of values. Scroll sideways on a small screen.

Agree on a couple of things up front. What should n = 0 return: an empty list, or a list holding one empty tree? Most versions of the problem expect an empty list. And is it fine for different trees in the output to share subtree objects? If the caller might modify a tree later, sharing is a bug waiting to happen.

Slow approach: every insertion order

Every BST on keys 1..n can be produced by inserting the keys in some order, root first. So one honest brute force generates all n! permutations, inserts each into an empty BST, serializes the shape, and keeps one tree per distinct serialization. It is easy to trust, which makes it a good checker, but n! grows far faster than the number of distinct trees: for n = 8 it builds 40,320 trees to find 1,430 distinct ones.

from itertools import permutations

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right


def all_bsts_slow(n):
    def insert(node, key):
        if node is None:
            return TreeNode(key)
        if key < node.val:
            node.left = insert(node.left, key)
        else:
            node.right = insert(node.right, key)
        return node

    def shape(node):
        if node is None:
            return "#"
        return "(" + shape(node.left) + str(node.val) + shape(node.right) + ")"

    found = {}
    for order in permutations(range(1, n + 1)):
        root = None
        for key in order:
            root = insert(root, key)
        found.setdefault(shape(root), root)
    return list(found.values()) if n else []
Brute force through permutations: O(n! · n) time.

Main approach: recurse on the root

Write build(lo, hi), which returns every BST on the keys lo to hi. If the range is empty, there is exactly one tree, the empty one, so return a list containing None (or null). That single placeholder is what lets the loops below work without special cases. Otherwise, for each candidate root r from lo to hi, get the list of left subtrees from build(lo, r − 1) and right subtrees from build(r + 1, hi), and for every pair create a new node r with that left and right child.

Correctness comes from the same fact as the counting version: once the root is r, the BST rule forces exactly the keys below r into the left subtree and the keys above r into the right. Different roots give different shapes, and within one root, different (left, right) pairs give different shapes, so nothing is produced twice.

from functools import lru_cache

def all_bsts(n):
    if n == 0:
        return []

    @lru_cache(maxsize=None)
    def build(lo, hi):
        if lo > hi:
            return (None,)  # one way to build an empty tree
        trees = []
        for root in range(lo, hi + 1):
            for left in build(lo, root - 1):
                for right in build(root + 1, hi):
                    trees.append(TreeNode(root, left, right))
        return tuple(trees)

    return list(build(1, n))
Python: recursion with a cache on (lo, hi). Uses TreeNode from the block above.
class TreeNode {
  constructor(val = 0, left = null, right = null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

function allBsts(n) {
  if (n === 0) return [];
  const memo = new Map();

  function build(lo, hi) {
    if (lo > hi) return [null];
    const key = lo + "," + hi;
    if (memo.has(key)) return memo.get(key);
    const trees = [];
    for (let root = lo; root <= hi; root++) {
      for (const left of build(lo, root - 1)) {
        for (const right of build(root + 1, hi)) {
          trees.push(new TreeNode(root, left, right));
        }
      }
    }
    memo.set(key, trees);
    return trees;
  }

  return build(1, n);
}
JavaScript: the same recursion with a Map keyed by the range.

The Python cache returns tuples so that nobody can append to a cached list by accident. Trace n = 3 with root 2: build(1, 1) gives the single node 1, build(3, 3) gives the single node 3, and one tree comes out. Root 1 pairs the empty left with the two trees on keys 2 and 3, and root 3 mirrors that, for 5 in total.

Shared subtrees: a feature and a trap

With the cache, build(2, 3) is computed once and its two trees are hung under root 1 in two different answers, and the same node objects can show up under other roots too. Even without a cache, the code above reuses the left and right objects across several new roots. That is fine for a read-only answer, and the problem's checker only reads. If the interviewer asks for fully independent trees, clone each subtree before attaching it, which raises memory to O(n) nodes per tree in the output.

Complexity

Costs for n keys; Catalan(n) is the number of trees returned
ApproachTimeExtra space
All permutations, then dedupeO(n! · n)O(Catalan(n) · n) for kept trees
Recursion on the root, no cacheAbout O(n · Catalan(n)), with repeated subproblemsOutput plus O(n) stack
Recursion with a cacheProportional to the nodes created, at most about n · Catalan(n)Output, with subtrees shared
Costs for n keys; Catalan(n) is the number of trees returned. Scroll sideways on a small screen.

Catalan(n) grows roughly like 4^n / n^1.5, so this problem is always exponential in n. That is fine: the output itself is exponential, and no algorithm can return it faster than it can write it down. Say this explicitly, because it is the honest answer to "can you do better?"

Edge cases

  • n = 0: return an empty list unless told otherwise. Returning [None] is a common mismatch with the judge.
  • n = 1: one tree with a single node.
  • Larger n: n = 8 already yields 1,430 trees and n = 10 yields 16,796, so check memory if the interviewer asks about scaling.
  • Callers that mutate results: shared subtrees mean editing one tree can change others. Clone when independence is required.

Common mistakes

  • Returning an empty list for an empty range. Then the nested loops never run, and every tree with an empty child disappears.
  • Building nodes once per root and mutating their children inside the loop, so every answer ends up pointing at the last pair tried.
  • Using a mutable cached list in Python and appending to it from a caller, which silently corrupts later results.
  • Counting instead of building, or building and then counting, when only one was asked for. Read which version you were given.
  • Claiming polynomial time. The output alone is exponential.

Explaining it

Fictional example

A clear pitch for the generator
Candidate
I'll write build of lo and hi that returns every BST on that range. An empty range returns a list with one empty tree, so the loops still pair it with the other side.
Candidate
For each root, I take every left tree from the smaller keys and every right tree from the larger keys and make a new root node for each pair.
Candidate
There are Catalan of n trees in the answer, so the cost is exponential no matter what. I'll memoize ranges so subtrees are built once, and mention that the trees then share nodes.

Next problems

If you have not done the counting version, start with Unique Binary Search Trees, which gives the size of this problem's output. The very same "split, recurse on both sides, combine every pair" loop solves Different Ways to Add Parentheses, with operator positions in place of roots. Broader tree questions live on the data structure interview questions page.

Practicing it with Natively

Generation problems are easy to get almost right, so practice tracing small cases aloud. Natively can read the problem from a screenshot during a practice run and suggest an approach to compare against yours, and it transcribes your mock session on your own computer so you can check whether you raised the shared-subtree point unprompted. Learn more about an AI interview assistant.

Questions people ask

How do you generate all unique binary search trees for 1 to n?

Write build(lo, hi) that returns every BST on that range. For each root r, combine every tree from build(lo, r - 1) with every tree from build(r + 1, hi) under a new node r. An empty range returns a list holding one empty tree.

What is the time complexity of Unique Binary Search Trees II?

The output contains Catalan(n) trees, which grows roughly like 4^n / n^1.5, so any solution is exponential. The recursive generator spends about O(n · Catalan(n)) work, close to the size of the output.

Why return a list with one null for an empty range?

An empty subtree is one valid choice. Returning an empty list instead would make the nested loops skip every root that has an empty side, and those trees would be lost.

Is it a problem that generated trees share subtrees?

Not for a read-only answer, which is what the problem checks. If callers may modify the trees, clone each subtree before attaching it so the answers are independent.

Where to go next

Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.

Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.

Keep reading

Put it on your own machine.

A live-conversation assistant that runs locally. Your conversations stay on your machine.

macOS 12+ · Windows 10/11

© 2026 Natively AI Private Limited

Source-available under the Natively Personal Use Source License v1.0 · IP geolocation by DB-IP