`

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

Unique Binary Search Trees 相比这道题目要难一些,要求输出所有可能的二叉查找树。在for循环中用递归解决。代码如下:
/**
 * 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) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        if(n == 0) return list;
        return getGenerate(1, n);
    }
    
    public List<TreeNode> getGenerate(int start, int n) {
        List<TreeNode> list = new ArrayList<TreeNode>();
        if(start > n) {
            list.add(null);
            return list;
        }
        for(int i = start; i <= n; i++) {
            List<TreeNode> left = getGenerate(start, i - 1);
            List<TreeNode> right = getGenerate(i + 1, n);
            for(TreeNode leftNode : left)
                for(TreeNode rightNode: right) {
                    TreeNode root = new TreeNode(i);
                    root.left = leftNode;
                    root.right = rightNode;
                    list.add(root);
                }
        }
        return list;
    }
}
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics