2014年4月21日 星期一

[LeetCode] Unique Binary Search Trees II

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
confused what "{1,#,2,3}" means? > read more on how binary tree is serialized on OJ.
Solution:O(n)
public class Solution {
    public ArrayList<TreeNode> generateTrees(int n) {
        return generateTrees(1,n);
    }
    
    public ArrayList<TreeNode> generateTrees(int a, int b){
        ArrayList<TreeNode> ret = new ArrayList<TreeNode>();
        
        if(a>b){
            ret.add(null);   
        }else if(a==b){
            ret.add(new TreeNode(a));
        }else if(a<b){
            for(int i=a;i<=b;i++){
                ArrayList<TreeNode> tmp1 = generateTrees(a,i-1);
                ArrayList<TreeNode> tmp2 = generateTrees(i+1,b);
                
                for(TreeNode n:tmp1){
                    for(TreeNode m:tmp2){
                        TreeNode tmp= new TreeNode(i);
                        tmp.left=n;
                        tmp.right=m;
                        ret.add(tmp);
                    }
                }
            }
        } 
        return ret;
    }
}

沒有留言:

張貼留言