Leetcode: Unique Binary Search Tree II
来源:互联网 发布:长虹电视怎样连接网络 编辑:程序博客网 时间:2024/05/21 10:29
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
public ArrayList<TreeNode> generateTrees(int n) {// Start typing your Java solution below// DO NOT write main() functionArrayList<TreeNode> res = new ArrayList<TreeNode>();generate(res, 1, n);return res;}public void generate(ArrayList<TreeNode> res, int start, int end){if(start > end){res.add(null);// reason of adding NULL is because OJ uses this format to store treesreturn;}for(int i = start; i <= end; i++){ArrayList<TreeNode> left = new ArrayList<TreeNode>();ArrayList<TreeNode> right = new ArrayList<TreeNode>();generate(left, start, i - 1);generate(right, i + 1, end);// i is current tree node, left stores left child node, right stores right child node// all nodes in left is smaller than i, all nodes in right is larger than i// if n == 2;// 1st iteration: left null, right 2;// 2nd iteration: left 1, right null;for(int j = 0; j < left.size(); j++){for(int k = 0; k < right.size(); k++){TreeNode root = new TreeNode(i);root.left = left.get(j);root.right = right.get(k);res.add(root);}}}}
- Leetcode: Unique Binary Search Tree II
- 【Leetcode】Unique Binary Search Tree II (DP)
- 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 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
- [LeetCode]Unique Binary Search Trees II
- [leetcode]Unique Binary Search Trees II
- ecshop常见错误列表 错误 /temp/compiled/top10.lbi.php on line 22
- Ubutu 12.04LTS 安装搜狗拼音输入法+搜狗皮肤 步骤详解
- HyperDex: A Distributed, Searchable Key-Value Store
- Codeforces Round #190 (Div. 2) 水果俩水题
- Java定位CPU使用100%的方法
- Leetcode: Unique Binary Search Tree II
- selenium IDE(http://www.verydemo.com/demo_c128_i46046.html)
- Complete Checklist for Manual Upgrades to Oracle Database 12c Release 1 (12.1) [ID 1503653.1]
- 关于java.nio.ByteBuffer的一些杂七杂八。
- 02-VMware9上面安装Ubuntu 12.10
- 使用Canvas的drawTextOnPath方法实现沿着Path绘制文本
- 如何在一台主机上安装多个版本oracle 数据库?
- Vc++ new delete 线程非安全性
- scott用户sql操作