leetcode 95. 不同的二叉搜索树 II
2019-03-15 16:10
302 查看
-
题目链接 https://leetcode-cn.com/problems/unique-binary-search-trees-ii/submissions/
-
题目描述
给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
-
[code]输入: 3 输出: [ [1,null,3,2], [3,2,null,1], [3,1,null,null,2], [2,1,3], [1,null,2,null,3] ] 解释: 以上的输出对应以下 5 种不同结构的二叉搜索树: 1 3 3 2 1 \ / / / \ \ 3 2 1 1 3 2 / / \ \ 2 1 2 3
解题思路
- 题目是求中序遍历是[1..n]的所有搜索二叉树。以[1..n]的任意元素i为根节点,i的所有可能左子树为[1..i-1]的所有二叉树。i的右子树为[i+1..n]的所有二叉树。
代码
- C++
[code]class Solution { public: vector<TreeNode*> generateTrees(int n) { if (not n) return vector<TreeNode*>{}; return _dfs(1, n); } vector<TreeNode*> _dfs(int start, int end){ vector<TreeNode*> res; if(start > end){ res.push_back(NULL); return res; }else{ for(int i = start; i <= end; i++){ vector<TreeNode*> left = _dfs(start, i - 1); vector<TreeNode*> right = _dfs(i + 1, end); for(TreeNode* l: left) for(TreeNode* r: right){ TreeNode* t = new TreeNode(i); t->left = l; t->right = r; res.push_back(t); } } } return res; } };
相关文章推荐
- LeetCode题库解答与分析——#95. 不同的二叉查找树 IIUniqueBinarySearchTreeII
- Leetcode 95. Unique Binary Search Trees II 二叉搜索树2 解题报告
- [LeetCode] 95. Unique Binary Search Trees II 唯一二叉搜索树 II
- leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法
- leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法
- LeetCode 95. Unique Binary Search Trees II(唯一二叉搜索树)
- 95. 不同的二叉搜索树 II(来源LeetCode)
- leetcode 95. Unique Binary Search Trees II-分治算法|动态规划|卡特兰数
- LeetCode--Unique Binary Search Trees (不同二叉搜索树的个数)Python
- LeetCode力扣之95. Unique Binary Search Trees II
- [LeetCode]95.Unique Binary Search Trees II
- leetcode 95. Unique Binary Search Trees II | Java最短代码实现
- [LeetCode] Unique Binary Search Trees II 独一无二的二叉搜索树之二
- LeetCode 95.Unique Binary Search Trees II
- LeetCode-63. 不同路径 II
- leetcode - 95.Unique Binary Search Trees II
- LeetCode 272. Closest Binary Search Tree Value II(二叉搜索树查找)
- [leetcode] 95. Unique Binary Search Trees II
- 【LeetCode】95.Unique Binary Search Trees II(Medium)解题报告
- leetcode 95. Unique Binary Search Trees II(dp)