Online Judge Solutions

Tuesday, December 30, 2014

Unique Binary Search Trees

Given n, how many structurally unique BST's (binary search trees) that store values 1...n?
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

 
class Solution {
public:
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    int numTrees(int n) {
       if (n < 2) return 1;
       int ret = 0;
       for(int i = 0; i <n; i++)
           ret += numTrees(i)*numTrees(n-i-1);
       return ret;
    }
};
 
class Solution {
public:
    /**
     * @paramn n: An integer
     * @return: An integer
     */
    int numTrees(int n) {
        vector<int> count(n+1, 0);
        count[0] = 1;
        for(int i = 1; i <= n; i++) 
            for(int j = 0; j <i; j++)
                count[i] += count[j]*count[i-j-1]; 
        
        return count[n];
    }
};

No comments:

Post a Comment