搜索此博客

2012年8月30日星期四

Unique Binary Search Trees


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

Let's first see some basic cases,
If n==0, the root is null, then the number of BST is 1. numTrees(0)=1.
If n==1, the root is 1, then the number of BST is 1. numTrees(1)=1.
If n==2, we can either has 1(root)2(right) or 2(root)1(left), then the number of BST is 2. numTrees(2)=2.
The key idea of this problem is that each tree of n can be constructed by setting its root from 1, 2.. to n, and construct it's left tree and right tree recursively. For example, in the above diagram, we iterate from 1 to 3, and for 1, we can only have right subtrees with two nodes, then we calll numTrees(0) *numTrees(2) and add the result. then we pick 2 to be the root, and we can only have 2 and 3 as left and right trees accordingly, which is to call numTrees(1) * numTrees (1). Then we pick 3 as root, we call numTrees(2)*numTrees(0). However, we even do not need a recursion, but use an array to keep intermediate result. Further, you can find that the result is quite symmetric, that we even do not need to iterate a full cycle, but just reach the half, i.e., n/2. The second half should have the same number of trees as the first half.

01 public int numTrees(int n) {
02     if(n==0)
03         return 1;
04     if(n==1||n==2)
05         return n;
06     int[] array=new int[n+1];
07   
08     array[0]=1;
09     array[1]=1;
10     array[2]=2;
11   
12     for(int i=3;i<=n;i++)
13     {
14         int j;
15         for(j=1;j<=i/2;j++)
16         {
17             array[i]+=array[i-j]*array[j-1]*2;
18         }
19       
20         if(i%2==1)
21         {
22             array[i]+=array[i-j]*array[i-j];
23         }          
24     }      
25     return array[n];      
26 }

没有评论:

发表评论