Skip to content

Commit 883a1de

Browse files
committed
Unique Binary Search Trees II
1 parent b010162 commit 883a1de

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

UniqueBinarySearchTreesII.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
3+
*
4+
* For example,
5+
* Given n = 3, your program should return all 5 unique BST's shown below.
6+
*
7+
* 1 3 3 2 1
8+
* \ / / / \ \
9+
* 3 2 1 1 3 2
10+
* / / \ \
11+
* 2 1 2 3
12+
*/
13+
14+
import java.util.ArrayList;
15+
16+
public class UniqueBinarySearchTreesII {
17+
public ArrayList<TreeNode> generateTrees(int n) {
18+
return buildBST(1, n);
19+
}
20+
21+
private ArrayList<TreeNode> buildBST(int min, int max) {
22+
ArrayList<TreeNode> ret = new ArrayList<TreeNode>();
23+
if (min > max) {
24+
ret.add(null);
25+
return ret;
26+
}
27+
if (min == max) {
28+
ret.add(new TreeNode(min));
29+
return ret;
30+
}
31+
for (int i = min; i <= max; i++) {
32+
ArrayList<TreeNode> leftTrees = buildBST(min, i - 1);
33+
ArrayList<TreeNode> rightTrees = buildBST(i + 1, max);
34+
for (TreeNode l : leftTrees) {
35+
for (TreeNode r : rightTrees) {
36+
TreeNode root = new TreeNode(i);
37+
root.left = l;
38+
root.right = r;
39+
ret.add(root);
40+
}
41+
}
42+
}
43+
return ret;
44+
}
45+
}

0 commit comments

Comments
 (0)