KatInterview

95. Unique Binary Search Trees II

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks us to generate all structurally unique Binary Search Trees (BSTs) that have nodes with unique values from 1 to n. The core of the problem lies in the definition of a BST: for any node with value i, all values in its left subtree must be less than i, and all values in its right subtree must be greater than i. This property naturally suggests a recursive, divide-and-conquer approach.

Solution

Unique Binary Search Trees II in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
        if n == 0:
            return []
        
        # Memoization cache. Key: (start, end) tuple.
        memo = {}

        def build(start: int, end: int) -> List[Optional[TreeNode]]:
            # Base case: if the range is invalid, return a list with a single None.
            # This represents an empty subtree.
            if start > end:
                return [None]
            
            # If the result for this range is already in the cache, return it.
            if (start, end) in memo:
                return memo[(start, end)]

            all_trees = []
            # Iterate through all numbers in the range [start, end] to use as the root.
            for i in range(start, end + 1):
                # Recursively generate all possible left subtrees.
                left_subtrees = build(start, i - 1)
                # Recursively generate all possible right subtrees.
                right_subtrees = build(i + 1, end)

                # Combine each left subtree with each right subtree.
                for left in left_subtrees:
                    for right in right_subtrees:
                        # Create a new root node with the current number.
                        root = TreeNode(i, left, right)
                        # Add the newly formed tree to the list of all trees.
                        all_trees.append(root)
            
            # Cache the result and return it.
            memo[(start, end)] = all_trees
            return all_trees

        return build(1, n)

Unique Binary Search Trees II in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) {
            return new ArrayList<>();
        }
        // Memoization table. memo[i][j] stores the list of trees for range [i, j].
        List<TreeNode>[][] memo = new List[n + 1][n + 1];
        return build(1, n, memo);
    }

    private List<TreeNode> build(int start, int end, List<TreeNode>[][] memo) {
        // Base case: if the range is invalid, return a list with a single null.
        // This represents an empty subtree.
        if (start > end) {
            List<TreeNode> list = new ArrayList<>();
            list.add(null);
            return list;
        }

        // If the result for this range is already computed, return it.
        if (memo[start][end] != null) {
            return memo[start][end];
        }

        List<TreeNode> allTrees = new ArrayList<>();
        // Iterate through all numbers in the range [start, end] to use as the root.
        for (int i = start; i <= end; i++) {
            // Recursively generate all possible left subtrees.
            List<TreeNode> leftSubtrees = build(start, i - 1, memo);
            // Recursively generate all possible right subtrees.
            List<TreeNode> rightSubtrees = build(i + 1, end, memo);

            // Combine each left subtree with each right subtree.
            for (TreeNode left : leftSubtrees) {
                for (TreeNode right : rightSubtrees) {
                    // Create a new root node with the current number.
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    // Add the newly formed tree to the list of all trees.
                    allTrees.add(root);
                }
            }
        }

        // Cache the result and return it.
        memo[start][end] = allTrees;
        return allTrees;
    }
}

Unique Binary Search Trees II in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<TreeNode*> generateTrees(int n) {
        if (n == 0) {
            return {};
        }
        // Memoization table. memo[i][j] stores the list of trees for range [i, j].
        memo.resize(n + 1, vector<vector<TreeNode*>>(n + 1));
        return build(1, n);
    }

private:
    vector<vector<vector<TreeNode*>>> memo;

    vector<TreeNode*> build(int start, int end) {
        // Base case: if the range is invalid, return a list with a single null pointer.
        // This represents an empty subtree.
        if (start > end) {
            return {nullptr};
        }

        // If the result for this range is already computed, return it.
        // An empty vector in memo indicates 'not computed' because even for a null-tree,
        // the result is a vector with one element (nullptr), not an empty vector.
        if (!memo[start][end].empty()) {
            return memo[start][end];
        }

        vector<TreeNode*> allTrees;
        // Iterate through all numbers in the range [start, end] to use as the root.
        for (int i = start; i <= end; ++i) {
            // Recursively generate all possible left subtrees.
            vector<TreeNode*> leftSubtrees = build(start, i - 1);
            // Recursively generate all possible right subtrees.
            vector<TreeNode*> rightSubtrees = build(i + 1, end);

            // Combine each left subtree with each right subtree.
            for (TreeNode* left : leftSubtrees) {
                for (TreeNode* right : rightSubtrees) {
                    // Create a new root node with the current number.
                    TreeNode* root = new TreeNode(i);
                    root->left = left;
                    root->right = right;
                    // Add the newly formed tree to the list of all trees.
                    allTrees.push_back(root);
                }
            }
        }

        // Cache the result and return it.
        return memo[start][end] = allTrees;
    }
};

Unique Binary Search Trees II in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function generateTrees(n: number): Array<TreeNode | null> {
    if (n === 0) {
        return [];
    }
    
    // Memoization cache. Key is "start,end", value is the list of trees.
    const memo = new Map<string, Array<TreeNode | null>>();

    function build(start: number, end: number): Array<TreeNode | null> {
        // Base case: if the range is invalid, return an array with a single null.
        // This represents an empty subtree.
        if (start > end) {
            return [null];
        }

        const key = `${start},${end}`;
        // If the result for this range is already in the cache, return it.
        if (memo.has(key)) {
            return memo.get(key)!;
        }

        const allTrees: Array<TreeNode | null> = [];
        // Iterate through all numbers in the range [start, end] to use as the root.
        for (let i = start; i <= end; i++) {
            // Recursively generate all possible left subtrees.
            const leftSubtrees = build(start, i - 1);
            // Recursively generate all possible right subtrees.
            const rightSubtrees = build(i + 1, end);

            // Combine each left subtree with each right subtree.
            for (const left of leftSubtrees) {
                for (const right of rightSubtrees) {
                    // Create a new root node with the current number.
                    const root = new TreeNode(i, left, right);
                    // Add the newly formed tree to the list of all trees.
                    allTrees.push(root);
                }
            }
        }
        
        // Cache the result and return it.
        memo.set(key, allTrees);
        return allTrees;
    }

    return build(1, n);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.