Topic:
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
Solving:
With recursive thinking, when there are only 0 or 1 nodes, there is only one; n nodes have f (n):
The left can have n-1 nodes, the right 0 nodes, according to symmetry can be interchanged around, at this time there are 2*f (n-1) *f (0);
One side 1, the other side n-2, this time has 2*f (1) *f (n-2);
One side two, one side N-3, this time has 2*f (2) *f (n-3);
。。。。。。
If n is odd, both sides are N/2, this time there is f (N/2) *f (N/2), if n is even, one side N/2 (n/2+1), 2*f (N/2) *f;
Code:
public static int numtrees (int n) { if (n==1| | n==0) return 1; int sum=0; if (n%2==0) {for (int k=n-1;k>=n/2;k--) { sum+=2*numtrees (k) *numtrees (n-1-k); } return sum; } else {for (int k=n-1;k>n/2;k--) { sum+=2*numtrees (k) *numtrees (n-1-k); } Return Sum+numtrees (N/2) *numtrees (N/2);} }
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode96_unique Binary Search Trees (1 to n how many different two-fork lookup trees can be formed by these nodes) Java troubleshooting