Leetcode–Unique Binary Search Trees II

The Problem:

Given 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

Notes:

  1. Same observation as Unique Binary Search Trees : for each i being the root, it has left subtrees of the number as i-1 nodes unique BST , its has unique right subtree of the number as n-i nodes unique BST.
  2. For each root node i, construct a list of its left subtrees with nodes of [start, i-1], and a list of its right subtrees with nodes of [i+1, end]; then get all the possible left right subtree combo, and add to result.

Java Solution

/**
 * Definition for binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; left = null; right = null; }
 * }
 */
public class Solution {
    public List<TreeNode> generateTrees(int n) {
        return constructTree(1, n);
    }
    
    private List<TreeNode> constructTree(int start, int end ){
        List<TreeNode> result= new ArrayList<TreeNode>();
        if(start > end){
            result.add(null);
            return result;
        }
        if(start == end){
            result.add(new TreeNode(start));
            return result;
        }
            
        for(int i = start; i <= end; i++){
            List<TreeNode> leftNodes = constructTree(start, i-1);
            List<TreeNode> rightNodes = constructTree(i+1, end);
            for(int j = 0; j < Math.max(1,leftNodes.size()); j++){
                for(int k = 0; k < Math.max(1,rightNodes.size()); k++){
                    TreeNode root = new TreeNode(i);
                    if(leftNodes.size()!=0)
                        root.left = leftNodes.get(j);
                    if(rightNodes.size()!= 0)
                        root.right = rightNodes.get(k);
                    result.add(root);
                }
            }
        }
        return result;
    }
    
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s