lintcode-medium-Unique Binary Search Trees II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

 

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

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
    public List<TreeNode> generateTrees(int n) {
        // write your code here
        
        return generateTrees(1, n);
    }
    
    public List<TreeNode> generateTrees(int start, int end){
        List<TreeNode> res = new ArrayList<TreeNode>();
        
        if(start > end){
            res.add(null);
            return res;
        }
        
        if(start == end){
            res.add(new TreeNode(start));
            return res;
        }
        
        for(int mid = start; mid <= end; mid++){
            List<TreeNode> left = generateTrees(start, mid - 1);
            List<TreeNode> right = generateTrees(mid + 1, end);
            
            for(TreeNode left_child: left){
                for(TreeNode right_child: right){
                    TreeNode root = new TreeNode(mid);
                    root.left = left_child;
                    root.right = right_child;
                    res.add(root);
                }
            }
            
        }
        
        return res;
    }
    
}

 

posted @ 2016-04-07 12:48  哥布林工程师  阅读(98)  评论(0编辑  收藏  举报