**[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
注:此类找出所有可能情况的问题,一般有两种方法保存过渡的结果集,保存在递归函数的形参中,或者以返回值的形式返回。
/** * 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
- **[Lintcode]Unique Binary Search Trees II 不同的二叉查找树 II
- 164.Unique Binary Search Trees II-不同的二叉查找树 II(中等题)
- Unique Binary Search Trees II 二叉查找树的路径
- Unique Binary Search Trees II 二叉树的种类
- LeetCode OJ 之 Unique Binary Search Trees II (不同的二叉搜索树 - 二)
- lintcode:Unique Binary Search Trees II
- Unique Binary Search Trees II --lintcode
- LeetCode 95. Unique Binary Search Trees II&96. Unique Binary Search Trees--动态规划,二叉树
- LeetCode-95-Unique Binary Search Trees II 二叉树
- Unique Binary Search Trees II
- Unique Binary Search Trees II
- Unique Binary Search Trees II
- Unique Binary Search Trees II
- Unique Binary Search Trees (& II)
- Unique Binary Search Trees II
- Unique Binary Search Trees II
- Unique Binary Search Trees II
- Unique Binary Search Trees II
- 初识JS
- 学生成绩管理系统java结业项目
- 在浏览器中禁止复制与粘贴
- 自己对互斥和同步的理解
- 观察者模式
- **[Lintcode]Unique Binary Search Trees II 不同的二叉查找树 II
- cuda编程入门示例3---数组求和
- 编译BFS出现aclocal.m4和Error: unknown pseudo-op: `.ule'的错误
- 30天自制操作系统day3-HLT实现
- 协方差矩阵的意义
- linux fedora 24 source 读取 配置文件 例如 profile
- 用VIM替换掉文件内容里的“\r\n”
- [UNIX系统编程] I/O缓冲
- linux进程间通信----之使用匿名管道