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
 ***/

class Solution {
public:
       int getnumTrees(int st, int ed) {
              if(st >= ed) return 1;

              int sum = 0;
              for(int i=st; i<=ed; i++) {
                     sum += getnumTrees(st, i-1) * getnumTrees(i+1, ed);
              }
              return sum;
       }

       int numTrees(int n) {
              // Start typing your C/C++ solution below
              // DO NOT write int main() function
              return getnumTrees(1, n);
       }

};

Comments

  1. Total number of possible Binary Search Trees with n different
    keys = Catalan number Cn = (2n)!/(n+1)!*n!

    ReplyDelete

Post a Comment

Popular posts from this blog

Coin in Line