Unique Binary Search Trees Series

Unique Binary Search Trees Series

Question

Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?

For example,

Given n = 3, there are a total of 5 unique BST’s.

1
2
3
4
5
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

Analysis

LeetCode Discuss Detailed explanation

对于数字范围1-n,可能任意选择其中的x作为树的根,以x为根的树的种类数是[1,x-1]和[x+1,n]可形成的左右子树个数的乘积和。

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
public class Solution {
public int numTrees(int n) {
int[] numTrees=new int[n+1];
numTrees[0]=1;
numTrees[1]=1;
for(int i=2;i<=n;i++){
for(int j=1;j<=i;j++){
numTrees[i]+=numTrees[j-1]*numTrees[i-j];
}
}
return numTrees[n];
}
}

Unique Binary Search Trees Series II

Question

Given an integer n, generate all structurally unique BST’s (binary search trees) that store values 1…n.

For example,

Given n = 3, your program should return all 5 unique BST’s shown below.

1
2
3
4
5
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3

Analysis

LeetCode Discuss Explanation

原理同上,只不过得到的不是树的个数而是左右子树的节点,然后利用循环进行组合

Code

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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<TreeNode> generateTrees(int n) {
List<TreeNode> res=new ArrayList<TreeNode>();
if(n==0) return res;
return helper(1,n);
}
private List<TreeNode> helper(int start, int end){
List<TreeNode> res=new ArrayList<TreeNode>();
if(start>end){
res.add(null);
return res;
}
for(int i=start;i<=end;i++){
List<TreeNode> left=helper(start,i-1);
List<TreeNode> right=helper(i+1,end);
for(TreeNode lchild:left){
for(TreeNode rchild:right){
TreeNode root=new TreeNode(i);
root.left=lchild;
root.right=rchild;
res.add(root);
}
}
}
return res;
}
}