Leetcode-95-不同的二叉搜索树Ⅱ

题目

给定一个整数 n,生成所有由 1 … n 为节点所组成的 二叉搜索树

image-20200721092547034

递归

遍历1...n中的所有元素, 以当前元素为根结点. 计算所有可能的左子树和右子树, 并将所有左子树-右子树组合拼接到根结点上.

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* 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 generateTrees(1, n);
}

public List<TreeNode> generateTrees(int start, int end) {
ArrayList<TreeNode> roots = new ArrayList<>();
if (start > end) {
roots.add(null);
return roots;
}
for (int i = start; i <= end; i++) {
List<TreeNode> leftTrees = generateTrees(start, i - 1); // 获取所有可能的左子树
List<TreeNode> rightTrees = generateTrees(i + 1, end); // 获取所有可能的右子树

// 遍历所有左子树和右子树的组合, 拼接到根结点上
for (TreeNode leftTree : leftTrees) {
for (TreeNode rightTree : rightTrees) {
TreeNode root = new TreeNode(i, leftTree, rightTree);
roots.add(root);
}
}
}
return roots;
}
}

image-20200721092906650