Unique Binary Search Trees LeetCode Solution


   1         3     3      2      1
    \       /     /      / \      \
     3     2     1      1   3      2
    /     /       \                 \

   2     1         2                 3
Approach:
Let us consider result[i] be the number of unique binary search trees for i. The number of trees are determined by the number of subtrees which have different root node. For example,

i=0, result[0]=1 //empty tree

i=1, result[1]=1 //one tree

i=2, result[2]=result[0]*result[1] // 0 is root
            + result[1]*result[0] // 1 is root

i=3, result[3]=result[0]*result[2] // 1 is root
            + result[1]*result[1] // 2 is root
            + result[2]*result[0] // 3 is root

i=4, result[4]=result[0]*result[3] // 1 is root
            + result[1]*result[2] // 2 is root
            + result[2]*result[1] // 3 is root
            + result[3]*result[0] // 4 is root
..
..
..


i=n, result[n] = sum(result[0..k]*result[k+1...n]) 0 <= k < n-1

Python Code:

class Solution(object):
    def numTrees(self, n):
        result = [0]*(n+1)
        result[0],result[1] = 1,1
        for i in range(2,n+1):
            for j in range(0,i):
                result[i] = result[i]+result[j]*result[i - j - 1]
        
        return result[n]
Java Code:

class Solution {
    public int numTrees(int n) {
int[] result = new int[n + 1];

result[0] = 1;
result[1] = 1;

for (int i = 2; i <= n; i++) {
for (int j = 0; j <= i - 1; j++) {
result[i] = result[i] + result[j] * result[i - j - 1];
}
}

return result[n];
}

}

Post a Comment

0 Comments