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
Analysis: First of all, we consider from the angle of classification, when the root node of BST is,.. The number of BST trees corresponding to N. When we determine the root node K of BST, the number of BST with K as the root node equals the number of left BST subtrees multiplied by the number of right BST subtrees. It is also worth noting that the number of BST for a given node is certain, according to which we can do further optimization. The code is as follows:
classSolution { Public: intNumtrees (intN) {if(n = =0|| n = =1)return 1; intresult =0; for(inti =1; I <= n/2; i++) Result+ = Numtrees (i-1) *numtrees (ni); return(n%2==0)? (2*result):(pow (numtrees (n/2),2) +2*result); }};
In addition, there is the phrase "When we determine the root node of BST K, then the number of BST with K as the root node equals the number of left BST subtree multiplied by the number of right BST subtree", we can use dynamic programming method solution. The recursive formula can be written as:
f (i) = SUM (f (k-1) *f (i-k)) where k =,... I. Time complexity is O (n^2) and space complexity is O (n). The code is as follows:
classSolution { Public: intNumtrees (intN) {vector<int> F (n+1,0); f[0] =1; for(inti =1; I <= N; i++) for(intK =1; K <= i; k++) F[i]+ = f[k-1] * f[i-K]; returnF[n]; }};
Leetcode:unique Binary Search Trees