2014年2月21日星期五

LeetCode - 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 binary tree
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; left = null; right = null; }
 * }
 */
public class Solution {
    public ArrayList<TreeNode> generateTrees(int n) {
        return genTrees(1, n);
    }
    
    public ArrayList<TreeNode> genTrees(int a, int b) {
        ArrayList<TreeNode> trees = new ArrayList<TreeNode>();
        if(a>b) {
            trees.add(null);
        } else if(a==b) {
            trees.add(new TreeNode(a));
        } else {
            for(int i=a;i<=b;i++) {
                ArrayList<TreeNode> lefts = genTrees(a, i-1);
                ArrayList<TreeNode> rights = genTrees(i+1, b);
                for(TreeNode l : lefts) {
                    for(TreeNode r : rights) {
                        TreeNode tree = new TreeNode(i);
                        tree.left = l;
                        tree.right = r;
                        trees.add(tree);
                    }
                }
            }
        }
        return trees;
    }
}

没有评论:

发表评论