GivenN, how many structurally uniqueBST ' 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
Given an n value, then from 1.2.3 .... n number of N, can build several binary sort tree.
The idea of solving the problem is: to traverse 1 to n number, each element as the root node, according to the idea of the middle sequence traversal, the small root node on the left, greater than the root node on the right. The number of the left sub-binary tree and the number of the right binary tree are calculated and multiplied to get the two-fork tree. The question is whether the feeling can be solved according to the idea of recursion.
Recursive thinking:
public int numtrees (int n) { if (n==0| | N==1) return 1; if (n==2) return 2; int num=0; for (int i=1;i<=n;i++)//root node { num+=numtrees (i-1) *numtrees (n-i);//Zuozi Binary sort tree number of builds * Right subtree two forks sort tree build number } return num; }
Although the logic is right, Leetcode hints timelimited. That is, recursion timed out.
Let's have a try. The number of builds that have been solved as root nodes is first saved with an array, and then called when the subsequent nodes are solved.
1) define an array first
2) Array[0] Indicates the number of nodes is 0, array[0]=1;
3) Array[1] indicates that there is only one case for solving 1 nodes: The number of left nodes and the number of right nodes are 0 i.e. a[0]*a[0];
4) array[2] indicates that there are only two cases for solving 2 nodes: The number of left nodes and the number of right nodes are a[1]*a[0],a[0]*a[1]
5) Array[3] indicates that 3 nodes are solved in only three cases: the number of left nodes and the number of right nodes is a[2]*a[0],a[1]*a[1],a[0]*a[2]
And so on
We use code to implement the following
public int numtrees (int n) { int[] array=new int[n+1]; Array[0]=1; for (int i=1;i<=n;i++) {for (int j=0;j<i;j++) { array[i]+=array[j]*array[i-j-1]; } } return array[n]; }
[Java] LeetCode96 Unique Binary Search Trees