LeetCode 95. Unique Binary Search Trees II

Problem:

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1…n.

For example,
Given n = 3, your program should return all 5 unique BST’s shown below.

   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \
   2     1         2                 3

Solution:

Recursion with start and end.

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        if (n == 0) return new ArrayList<TreeNode>();
        return generate(1, n);
    }
    
    private List<TreeNode> generate(int s, int e) {
        List<TreeNode> re = new ArrayList<TreeNode>();
        if (s > e) {
            re.add(null);
            return re;
        }
        for (int i = s; i <= e; i++) {
            List<TreeNode> lefts = generate(s, i - 1);
            List<TreeNode> rights = generate(i + 1, e);
            for (TreeNode left: lefts) {
                for (TreeNode right: rights) {
                    TreeNode root = new TreeNode(i);
                    root.left = left;
                    root.right = right;
                    re.add(root);
                }
            }
        }
        return re;
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *