[leedcode 96] Unique Binary Search Trees II

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

 

confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.

/**
 * 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) {
        //拿到n个数字后,从中依次选取一个数作为根结点,分别从根节点分成的左右两个分支中选择一个节点作为左右子树的根节点
        return generate(1,n);
    }
    public List<TreeNode> generate(int start,int end){
        List<TreeNode> seq=new ArrayList<TreeNode>();
        if(start>end){
             seq.add(null);
        }
        else{
            for(int i=start;i<=end;i++){
            List<TreeNode> left=generate(start,i-1);
            List<TreeNode> right=generate(i+1,end);
            
            for(int li=0;li<left.size();li++){
                for(int ri=0;ri<right.size();ri++){
                    TreeNode root=new TreeNode(i);
                    root.left=left.get(li);
                    root.right=right.get(ri);
                    seq.add(root);
                }
            }
            }
        }
        return seq;
    }
}

 

posted @ 2015-07-16 20:51  ~每天进步一点点~  阅读(164)  评论(0编辑  收藏  举报