Question:
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
Solution:
First of all, please focus on the structure of the tree. We are figuring how many distinct structure could n nodes form. Values inside of these nodes are not important as long as I see.
Requirement:
Probability class.
Idea:
Level by level probability. We view each level as slots. Level one definitely only has one slot. We have to place only one ball(node). At level 2, we now have 2 slots! how many ways to place it? left, right, left&right.(only if we have 2 balls). And the next level number of slots is two times previous level number of slots.
class Solution { public: int factorial(int n){ return (n == 1 || n == 0) ? 1 : factorial(n - 1) * n; } int xChooseY(int x, int y){ return factorial(x) / (factorial(x-y)* factorial(y)) ; } //@param // previous level num of nodes // reminding number of nodes we could place //@return the number of unique ways int explore(int nodeNum, int reminder){ if(reminder == 0) return 1; //only previous possibility else { int ret = 0; int maxNumNode = nodeNum *2;// we gotta times 2 because of the tree structure int insertMax = min(reminder,maxNumNode); for(int i =1; i <= insertMax; i++){ //insert 1 ball, 2 ball... ret+= xChooseY(maxNumNode, i) *explore(i,reminder-i);//if insert i balls, what about next level? } return ret; } int numTrees(int n) { if(n == 0) return 0; else { return explore(1,n-1);// place one ball at level 1 and let's go! } } }