Skip to content

Instantly share code, notes, and snippets.

@wayetan
Created December 24, 2013 06:09
Show Gist options
  • Save wayetan/8109419 to your computer and use it in GitHub Desktop.
Save wayetan/8109419 to your computer and use it in GitHub Desktop.
Unique Binary Search Tree
/**
* 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 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
*/
public class Solution{
public int numTrees(int n) {
int[] count = new int[n + 1];
count[0] = 1;
count[1] = 1;
for(int i = 2; i <= n; i++){
for(int j = 0; j < i; j++){
count[i] += count[j] * count[i - j - 1];
}
}
return count[n];
}
}
/**
* Given n, generate all structurally unique BST's (binary search trees) that store values 1...n.
* Given n = 3, your program should return all 5 unique BST's shown below.
* 1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
*/
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; left = null; right = null; }
* }
*/
public class Solution{
public ArrayList<TreeNode> generateTrees(int n) {
if(n == 0) return generateTrees(1, 0);
return generateTrees(1, n);
}
public ArrayList<TreeNode> generateTrees(int start, int end) {
ArrayList<TreeNode> subTrees = new ArrayList<TreeNode>();
if(start > end){
subTrees.add(null);
return subTrees;
}
for(int i = start; i <= end; i++){
for(TreeNode left : generateTree(start, i - 1)){
for(TreeNode right : generateTrees(i + 1, end)){
TreeNode aTree = new TreeNode(i);
aTree.left = left;
aTree.right = right;
subTrees.add(aTree);
}
}
}
return subTrees;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment