Given N, how many structurally unique BST 's (binary search trees) that store values 1 ... n?
For example,
Given N = 3, there is a total of 5 unique BST ' s.
1 3 3 2 1 \// /\ 3 2 1 1 3 2 / / \ 2 1 2 3
intNumtrees (intN) {int*result =malloc((n +1)*sizeof(int)); if(n = =0|| n = =1) return 1; if(n = =2) return 2; result[0] = result[1] =1; result[2] =2; for(inti =3; I <= N; i++) { intTMP =0; Result[i]=0; for(intj =1; J <= I/2; J + +) TMP+ = Result[j-1] * Result[i-J]; Result[i]= tmp *2; if(I-(I/2) *2) Result[i]+ = Result[i/2] * Result[i/2]; } returnresult[n];}
- Select a value in the sequence as the root node, Saozi the right subtree, and can have the product of the remaining number permutations, respectively
- Because the left and right sides select the same number, you can separate both sides of the calculation
- When opening up space, it is necessary to open up n+1, and array of [n] Correspondence
Unique Binary Search Trees