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

来源:互联网 发布:天刀真武男捏脸数据 编辑:程序博客网 时间:2024/05/22 04:47

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