"096-unique binary search Trees (the only binary searching tree)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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
Main Topic
Given a two-fork search tree of n nodes, find out how many different types of two-fork search trees are in total.
Thinking of solving problems
Recursive formulas
F (k) *f (N-1-k): F (k) indicates that there are k nodes in the left subtree of the root node, the shape of which is f (k), and F (n-1-k) indicates that the right subtree has a n-1-k node.
F (n) = 2*f (n-1) + f (1) *f (n-2) + f (2) *f (n-3) + f (3) *f (n-4) + ... +f (n-2) *f (1)
Code Implementation
Algorithm implementation class
Public classSolution { Public int numtrees(intN) {if(N <=0) {return 0; }Else if(n = =1) {return 1; }int[] result =New int[n +1]; result[0] =0; result[1] =1;//Ask F (2) ... f (n) for(inti =2; I <= N; i++) {//Ask F (i)Result[i] =2* Result[i-1]; for(intj =1; J <= I-1; J + +) {Result[i] + = result[j]*result[i-1-J]; } }returnResult[n]; }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47333321"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "096-unique binary search Trees (the only binary searching tree)"