- [刷题防痴呆] 0095 - 不同的二叉搜索树 II (Uniq
- 0095. 不同的二叉搜索树 II
- [刷题防痴呆] 0700 - 二叉搜索树中的搜索 (Search
- [刷题防痴呆] 0098 - 验证二叉搜索树 (Validate
- Python小白 Leetcode刷题历程 No.96-N
- [刷题防痴呆] 0212 - 单词搜索 II (Word Sea
- LeetCode 95. 不同的二叉搜索树 II | Pytho
- [刷题防痴呆] 0173 - 二叉搜索树迭代器 (Binary
- [刷题防痴呆] 0669 - 修剪二叉搜索树 (Trim a B
- [刷题防痴呆] 0530 - 二叉搜索树的最小绝对差 (Mini
题目地址
https://leetcode.com/problems/unique-binary-search-trees-ii/description/
题目描述
95. Unique Binary Search Trees II
Given an integer n, generate all structurally unique BST's (binary search trees) that store values 1 ... n.
Example:
Input: 3
Output:
[
[1,null,3,2],
[3,2,null,1],
[3,1,null,null,2],
[2,1,3],
[1,null,2,null,3]
]
Explanation:
The above output corresponds to the 5 unique BST's shown below:
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
思路
每次一次选取一个结点为根,然后递归求解左右子树的所有结果,最后根据左右子树的返回的所有子树,依次选取然后接上(每个左边的子树跟所有右边的子树匹配,而每个右边的子树也要跟所有的左边子树匹配,总共有左右子树数量的乘积种情况)
关键点
- 注意, 这里有个细节, 就是如果是叶子节点, 需要加入null返回. 作为叶子结点占位.
代码
- 语言支持:Java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
public List<TreeNode> generateTrees(int n) {
if (n == 0) {
return new ArrayList<TreeNode>();
}
return helper(1, n);
}
private List<TreeNode> helper(int start, int end) {
List<TreeNode> result = new ArrayList<>();
if (start > end) {
result.add(null);
return result;
}
for (int i = start; i <= end; i++) {
List<TreeNode> left = helper(start, i - 1);
List<TreeNode> right = helper(i + 1, end);
for (TreeNode l: left) {
for (TreeNode r: right) {
TreeNode root = new TreeNode(i);
root.left = l;
root.right = r;
result.add(root);
}
}
}
return result;
}
}
网友评论