**[Lintcode]Unique Binary Search Trees II 不同的二叉查找树 II

Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.

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
分析:可以使用递归。与arraylsit递归不同,不能在递归函数的退出条件处做深拷贝从而保证每一种情况均被保存。这里的数据结构是TreeNode,因此只能每次在递归函数开始时创建新数组,这样保证每一种可能的组合均可以被保存。


注:此类找出所有可能情况的问题,一般有两种方法保存过渡的结果集,保存在递归函数的形参中,或者以返回值的形式返回。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @paramn n: An integer
     * @return: A list of root
     */
     //不能像数组一样在退出条件处深拷贝  不能将结果集放入参数
    public List<TreeNode> generateTrees(int n) {
        List<TreeNode> res = new ArrayList<TreeNode>();
        if(n == 0) {
            res.add(null);
            return res;
        }
        if(n == 1) {
            res.add(new TreeNode(1));
            return res;
        }
        return helper(1, n);
    }
    
    List<TreeNode> helper(int start, int end) {
        List<TreeNode> res = new ArrayList<TreeNode>();//要在此处新建数组!确保每次递归时,都是新的
        //每一层均返回一组TreeNode,但是只有最外层用作结果集。其他层仅供用来拼凑left或者right
        if(start > end) {
            res.add(null);
            return res;
        }
        
        if(start == end) {
            res.add(new TreeNode(start));
            return res;
        }
        
        for(int i = start; i <= end; i++) {
            List<TreeNode> left = helper(start, i - 1);
            List<TreeNode> right = helper(i + 1, end);
            for (TreeNode t1 : left) {
                for(TreeNode t2 : right) {
                    TreeNode t = new TreeNode(i);
                    t.left = t1;
                    t.right = t2;
                    res.add(t);
                }
            }
        }
        return res;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值