15% off all plans & roadmaps Use code
See plansLeetCode 95 · Solution & editorial
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Unique Binary Search Trees II is a Dynamic Programming (DP) Patterns problem, in the Catalan Numbers subpattern. The pattern covers fibonacci, Kadane, knapsack, LCS, LIS, edit distance, grid paths, and word break
Solve problems involving Catalan numbers: unique BSTs, parentheses combinations, polygon triangulation.
The reference solution runs in O(C_n * n^2) time and O(C_n * n) space.
Unique Binary Search Trees II has been reported in interviews at Amazon, Google.
The full editorial is part of Pro
It explains the core insight, the complexity analysis and the common mistakes, with a worked solution.
Unique Binary Search Trees II is a Dynamic Programming (DP) Patterns problem, in the Catalan Numbers subpattern. Once the approach above makes sense, write it yourself and then work through the neighbouring problems that reuse it.