【Leetcode】Unique Binary Search Tree II (DP)
来源:互联网 发布:js设置div display 编辑:程序博客网 时间:2024/05/23 23:39
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
这道题和一唯一的不同在于要求返回所有的树,所以需要知道几个特性
1. [1,2,3,4,...i-1,i,i+1...n]这样的数组中,以i为根节点,[1~i-1]为左子树,[i+1~n]为右子树所构造出来的BST具有唯一性
2. 每一个数建立左节点一定在左子树里找,建立右节点一定在右子树里找,就不会出错
代码如下
public ArrayList<TreeNode> generateTrees(int n) {return helper(1, n);}private ArrayList<TreeNode> helper(int left, int right) {ArrayList<TreeNode> result = new ArrayList<TreeNode>();if (left > right) {result.add(null);return result;}for (int i = left; i <= right; i++) {ArrayList<TreeNode> leftSub = helper(left, i - 1);ArrayList<TreeNode> rightSub = helper(i + 1, right);for (int j = 0; j < leftSub.size(); j++) {for (int k = 0; k < rightSub.size(); k++) {TreeNode root = new TreeNode(i);root.left = leftSub.get(j);root.right = rightSub.get(k);result.add(root);}}}return result;}
0 0
- 【Leetcode】Unique Binary Search Tree II (DP)
- Leetcode: Unique Binary Search Tree II
- leetcode-unique binary search tree II
- Unique Binary Search Tree II -LeetCode
- [leetcode][tree] Unique Binary Search Trees II
- Unique Binary Search Tree II
- LeetCode Week10: Edit Distance, Unique Binary Search Tree(I & II)
- LeetCode--Unique Binary Search Trees II(DP求BST)
- leetcode 95. Unique Binary Search Trees II(dp)
- [LeetCode] Unique Binary Search Tree
- LeetCode : Unique Binary Search Tree
- 【LeetCode】Unique Binary Search Tree
- [Leetcode]Unique binary search tree
- Unique Binary Search Tree -- LeetCode
- LeetCode: Unique Binary Search Trees II
- LeetCode : Unique Binary Search Trees II
- [LeetCode] Unique Binary Search Trees II
- leetcode Unique Binary Search Trees II
- BadImageFormatException : Could not load file or assembly or one of its dependencies.
- OpenCV入门(二十一)-- 绘制彩色图像的直方图
- Windows7 64 VS2010/2012 去掉VMware菜单
- iOS开发之静态库的制作
- 博客搬家
- 【Leetcode】Unique Binary Search Tree II (DP)
- Android 生命周期-笔记
- PHPMYADMIN简明安装教程
- 设计模式学习——模板方法模式
- Linux内核编译静态库的方法
- 虚函数的实现机制
- 【案例分析】Linux下如何查看端口占用情况
- opengl编程指南 第七版 源码有bug Page35 lines.c 红宝书
- 插入排序之算法研究