95. Unique Binary Search Trees II
来源:互联网 发布:宾得k3 知乎 编辑:程序博客网 时间:2024/04/30 06:37
Given an integer 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
这题和之前的Unique Binary Search Tree基本思路差不多,就是操作难度大了些。上一题只要求求出有多少种可能的结构,这次要求输出所有可能的结构。但是递归的思想还是一致的,如果说上一题还能说是dynamic programming,这题就是典型的divide and conquer。这里需要我们抓住的就是递归函数的返回值类型相同,我们最终要的是一个包含所有结构的数列,数列每个元素分别是不同结构的root。当然这是个NP的问题,我们需要在循环中使用递归,首先得循环肯定是从1到n每个轮流作为根节点,然后每次选定根节点之后,左子树和右子树的选择就是变成了同样性质的小规模问题,分别是i-1和n-i, 所以对于小问题我们同样返回一个数列,存着所有可能结果的根节点,那么对于大问题来说,只需要从两边的小问题的返回序列中依次选取不同的子树来作为一个完整的结果存起来。弄明白这个递归的过程,代码不言而喻。
class Solution {public: vector<TreeNode*> generateTrees(int n) { vector<TreeNode*> res; if (n == 0) return res; else return helper(1, n); } vector<TreeNode*> helper (int begin, int end) { vector<TreeNode*> res; if (begin > end) { res.push_back(NULL); return res; } for (int i = begin; i <= end; i++) { vector<TreeNode*> lefttree = helper(begin, i-1); vector<TreeNode*> righttree = helper(i+1, end); for (int j = 0; j < lefttree.size(); j++) { for (int k = 0; k < righttree.size(); k++) { TreeNode* root = new TreeNode(i); root->left = lefttree[j]; root->right = righttree[k]; res.push_back(root); } } } return res; }};
这里特地邀注明的一点就是在任何组成的vector里,NULL都会作为成员参与计数,所以不用担心左子树是NULL的情况下没法进行右子树的循环选择问题。
1 0
- [LeetCode]95.Unique Binary Search Trees II
- [Leetcode] 95. Unique Binary Search Trees II
- LeetCode --- 95. Unique Binary Search Trees II
- [leetcode] 95.Unique Binary Search Trees II
- [leetcode] 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II LeetCode
- ***LeetCode 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- Leetcode 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- LeetCode *** 95. Unique Binary Search Trees II
- 【LeetCode】95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- LeetCode 95. Unique Binary Search Trees II
- 95. Unique Binary Search Trees II
- LINQ to SQL语句 收藏系列
- 电梯算法题
- Android中实现自定义XMPP消息包收发
- 搭建kafaka的环境
- 51Nod 算法马拉松17 路径计数 莫比乌斯函数加暴力构图
- 95. Unique Binary Search Trees II
- Makefile经典教程
- Restful 应用分析
- 离散化的操作
- Android编译命令m, mm, mmm
- try...catch...finally的陷阱——加锁的线程开发经验分享
- RTMP 协议
- 运行.exe文件并获取返回值(使用WinExec和system的区别)
- MyEclipse10激活详解