leetcode95~Unique Binary Search Trees II

Given an integer 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

由上题可知,可行的BST数是相应的卡特兰数,此题是求解所有的树,思路是采用递归。
每次选取一个节点作为根节点,然后递归求解左右子树的结果,最后根据左右子树返回的所有子树,依次选取然后链接即可。

但是此题有个坑,网上流传的很多答案都是无法在leetcode中accept的,原因在于输入为0时,返回的结果是[[]],而正确结果是[],这点要格外注意!

public class UniqueBST95 {
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> res = new ArrayList<TreeNode>();
        if(n==0) return res;

        return helper(1,n); //从节点1开始到节点n,分别作为root节点
    }

    private List<TreeNode> helper(int start, int end) {
        List<TreeNode> res = new ArrayList<TreeNode>();
        if(start>end) {
            res.add(null);
            return res;
        }

        //以i作为根节点
        for(int i=start;i<=end;i++) {
            List<TreeNode> left = helper(start,i-1); //左子树由start...i-1构成
            List<TreeNode> right = helper(i+1,end); //右子树由i+1....end构成
            //null也是可以遍历到的
            for(TreeNode l : left) {
                for(TreeNode r : right) {
                    TreeNode root = new TreeNode(i);
                    root.left = l;
                    root.right = r;
                    res.add(root);
                }
            }
        }
        return res;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值