如果节点数= n,我们有
其中C(n)=加泰罗尼亚数=(2n)! / [(n + 1)! * n! ]
我理解#1。我可以使用BST属性[下面的代码]来做到这一点。谁能告诉我如何到达#2和#3?感谢。
public static long countBST_dp(int n) {
if(n == 0 || n == 1) return 1;
long[] arr = new long[n+1];
arr[0] = 1; arr[1] = 1;
for (int i = 2; i < arr.length; i++) {
int isum = 0;
for (int k = 1; k <= i; k++) {
isum += arr[k-1] * arr[i-k];
}
arr[i] = isum;
}
return arr[n];
}
答案 0 :(得分:3)
否。结构上不同的二叉树 - 在这里顺序无关紧要,所有顶点都是相同的 - 所有重要的是结构。因此,我们可以创建一个bijection - 给定一个BST,创建一个所有节点都相同的树。现在,给定两个不同的BST - 你将获得两个不同的树,节点是相同的(否则两个节点之间存在差异,因此树不是BST) - 所以我们的函数是{{3 }}。此外,还有一些BST可以生成&#34;任何结构树&#39; - 所以我们的功能是injective。
因为我们发现从{T | T is a BST of nodes [1,2,...,n]}
到{T | T is a binary tree where all nodes are identical}
的双射 - 两组的大小是相同的。因为我们知道大小为C(n)
的第一组,所以第二组也是。
否。二叉树= n! * C(n)
对于来自T
的每个树{T | T is a binary tree where all nodes are identical}
,我们可以生成n!
个不同的树,以便通过在节点上应用所有排列来使节点彼此不同。因此,存在|{T | T is a binary tree where all nodes are identical}| * n!
个不同的树,使得节点彼此不同。由于我们已经证明集合的大小是加泰罗尼亚数字,我们得到C(n)*n!
答案 1 :(得分:0)
对于#1,您可以观看:Count Number of Binary Search Tress given N Distinct Elements
对于#2,你可以看到:Number of Binary Trees with n nodes
基本思想是我们以节点为根,将剩下的子树分布在左右子树上,这是原始子树的较小子问题。
对于#3,它是不同二叉树的数量(#2)乘以每棵树的不同数量排列(n!)。把它想象为用n个数字的任何排列填充BST。
答案 2 :(得分:0)
<强> 2。结构上不同的二叉树数量= C(n)
来自维基百科,Catalan number满足递归关系:
C(0) = 1, C(1) = 1
C(n) = C(0)*C(n-1) + C(1)*C(n-2) + ... + C(n-1)*C(0)
表示h(n) = No. of structurally different binary trees with node n
,然后:
h(0) = 1
h(1) = 1
...
With n node, left subtree of root may have 0,1,...,n-1 nodes
accordingly right subtree have n-1,n-2,...,0 nodes, so:
h(n) = h(0)*h(n-1) + h(1)*h(n-2) + ... + h(n-1)*h(0) = C(n)
第3。二叉树的数量= n! * C(n)
如果修复了二叉树的结构,我们可以n
方式用n!
个不同的值“填充”树。
有C(n)
个结构,所以No. of binary trees = n! * C(n)
。