给定n构建最大值为n的二叉查找树——树的形态
种类
https://leetcode.com/problems/unique-binary-search-trees/
Given n, how many structurally unique BST’s (binary search trees) that store values 1…n?
For example,
Given n = 3, there are a total of 5 unique BST’s.
1 3 3 2 1
\ / / / \ \
3 2 1 1 3 2
/ / \ \
2 1 2 3
其实也是给定n个节点,判断一个二叉树有多少种形态。
思路:其实相当于将节点排成一个有序数组,从开始到结束,以中间某个节点为根,将树抻成两半。本质是卡特兰数。
C(2n)^n/n+1。
@checked
public int numTrees(int n) {
int[] arr = new int[n+1];
arr[0] = 1;//0个数时记为1种
for(int i = 1; i <= n; i++){
//n个数
for(int j = 1; j <= i; j++){
//以j为根
arr[i] += arr[j-1] * arr[i-j];//左边有j-1个数,右边有i-j个数
}
}
return arr[n];
}
打印树的结构
https://leetcode.com/problems/unique-binary-search-trees-ii/
将上面的各种结构的树打印出来
思路:
求(1,n)那么就循环以i为根求左子树(1,i-1)和右子树(i+1,