Skip to content

Commit a34a91b

Browse files
author
wangpeng
committed
feat(MEDIUM): add _95_generateTrees
1 parent f7f88d8 commit a34a91b

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package pp.arithmetic.leetcode;
2+
3+
import pp.arithmetic.Util;
4+
import pp.arithmetic.model.TreeNode;
5+
6+
import java.util.ArrayList;
7+
import java.util.List;
8+
9+
/**
10+
* Created by wangpeng on 2019-04-24.
11+
* 95. 不同的二叉搜索树 II
12+
* <p>
13+
* 给定一个整数 n,生成所有由 1 ... n 为节点所组成的二叉搜索树。
14+
* <p>
15+
* 示例:
16+
* <p>
17+
* 输入: 3
18+
* 输出:
19+
* [
20+
* [1,null,3,2],
21+
* [3,2,null,1],
22+
* [3,1,null,null,2],
23+
* [2,1,3],
24+
* [1,null,2,null,3]
25+
* ]
26+
* 解释:
27+
* 以上的输出对应以下 5 种不同结构的二叉搜索树:
28+
* <p>
29+
* 1 3 3 2 1
30+
* \ / / / \ \
31+
* 3 2 1 1 3 2
32+
* / / \ \
33+
* 2 1 2 3
34+
*
35+
* @see <a href="https://leetcode-cn.com/problems/unique-binary-search-trees-ii/">unique-binary-search-trees-ii</a>
36+
*/
37+
public class _95_generateTrees {
38+
public static void main(String[] args) {
39+
_95_generateTrees trees = new _95_generateTrees();
40+
List<TreeNode> treeNodes = trees.generateTrees(3);
41+
for (int i = 0; i < treeNodes.size(); i++) {
42+
Util.printTree(treeNodes.get(i));
43+
}
44+
}
45+
46+
/**
47+
* 二叉搜索树(二叉查找树):根节点,比左子树大,比右子树小
48+
* 解题思路:
49+
* 1、确定根节点
50+
* 2、确定左子树列表(list)
51+
* 3、确定右子树列表(list)
52+
* 4、循环左右子树,拿到树的list
53+
*
54+
* 对于树的题目,最根本的解题方案就是递归左右子树
55+
*
56+
* @param n
57+
* @return
58+
*/
59+
public List<TreeNode> generateTrees(int n) {
60+
if (n == 0) return new ArrayList<>();
61+
return generateNodeList(1, n);
62+
}
63+
64+
private List<TreeNode> generateNodeList(int si, int ei) {
65+
List<TreeNode> res = new ArrayList<>();
66+
if (si > ei) {
67+
res.add(null);
68+
return res;
69+
}
70+
if (si == ei) {
71+
res.add(new TreeNode(si));
72+
return res;
73+
}
74+
for (int i = si; i <= ei; i++) {
75+
List<TreeNode> leftSubTrees = generateNodeList(si, i - 1);
76+
List<TreeNode> rightSubTrees = generateNodeList(i + 1, ei);
77+
for (TreeNode left : leftSubTrees) {
78+
for (TreeNode right : rightSubTrees) {
79+
TreeNode node = new TreeNode(i);
80+
node.left = left;
81+
node.right = right;
82+
res.add(node);
83+
}
84+
}
85+
}
86+
return res;
87+
}
88+
}

0 commit comments

Comments
 (0)