LeetCode-95. Unique Binary Search Trees II
Description:
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
和第I题的区别是这题要返回所有的结果,不是结果的数目。所以要递归枚举:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<TreeNode> generate(int start, int end) { List<TreeNode> ret = new ArrayList<TreeNode>(); if(start > end) { ret.add(null); return ret; } for(int i=start; i<=end; i++) { List<TreeNode> lTree = generate(start, i-1); //生成左子树集合 List<TreeNode> rTree = generate(i+1, end); //生成右子树集合 for(int j=0; j<lTree.size(); j++) { for(int k=0; k<rTree.size(); k++) { TreeNode node = new TreeNode(i+1); //连接到根节点 node.left = lTree.get(j); node.right = rTree.get(k); ret.add(node); } } } return ret; } public List<TreeNode> generateTrees(int n) { if(n <= 0) return new ArrayList<TreeNode>(); return generate(0, n-1); } }
C++:
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<TreeNode *> generate(int start, int end) { vector<TreeNode* > ret; if (start > end) { ret.push_back(NULL); return ret; } for(int i = start; i <= end; i++) { vector<TreeNode* > lTree = generate(start, i - 1); vector<TreeNode* > rTree = generate(i + 1, end); for(int j = 0; j < lTree.size(); j++) for(int k = 0; k < rTree.size(); k++) { TreeNode *node = new TreeNode(i + 1); ret.push_back(node); node->left = lTree[j]; node->right = rTree[k]; } } return ret; } vector<TreeNode *> generateTrees(int n) { vector<TreeNode* > ret; if(n <= 0) return ret; return generate(0, n - 1); } };
同样的代码同样的测试数据Java代码为什么效率高这么多,难道是跑代码的服务器不一样?还是Java后台调用代码写的好?
作者:Pickle
声明:对于转载分享我是没有意见的,出于对博客园社区和作者的尊重一定要保留原文地址哈。
致读者:坚持写博客不容易,写高质量博客更难,我也在不断的学习和进步,希望和所有同路人一道用技术来改变生活。觉得有点用就点个赞哈。
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112835275-168981902.gif)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112841431-2047172832.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112847494-1544911856.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112904385-918783221.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111120143119-1302805212.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112856369-1466718103.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111112830416-794416355.jpg)
![](https://images2015.cnblogs.com/blog/735119/201701/735119-20170111113919510-1155220901.gif)