bst 删除节点
Problem statement: C++ program to find number of binary search trees with n nodes.
问题陈述: C ++程序查找具有n个节点的二进制搜索树的数量。
Input format: single integer n
输入格式:单整数n
Constraints: 0=<n<=15
约束: 0 = <n <= 15
Sample input: 4
样本输入: 4
Sample output: 14 binary search tree/trees are there for 4 nodes
输出示例: 14个二叉搜索树/四个树的树
Problem explanation:
问题说明:
The number of BSTs with n vertices is given by Catalan numbers. For n=0,1,2,3,4... Catalan numbers are 1,1,2,5,14... and so on.
具有n个顶点的BST的数量由加泰罗尼亚语数字给出。 对于n = 0,1,2,3,4 ...加泰罗尼亚语数字是1,1,2,5,14 ...依此类推。
Catalan numbers are given by Cn = (2n)!/(n+1)!*n! = count of BSTs with nodes n.
加泰罗尼亚数字由Cn =(2n)!/(n + 1)!* n! =节点为n的BST的计数 。
Catalan numbers are used here to find the count of BSTs because both satisfy same recurrence relation that is:
由于两者都满足相同的递归关系,因此此处使用加泰罗尼亚语数字查找BST的计数:
For n=0 number of trees is 1 i.e. empty tree. For subsequent values:
对于n = 0 ,树的数量为1,即空树。 对于后续值:
And, so on...
等等...
Solution:
解:
If we consider root as the ith node then:
如果我们将root视为第i 个节点,则:
i-1 nodes are there in left subtree.
i-1节点在左子树中。
n-i nodes are there in right subtree.
ni个节点在右子树中。
Let’s denote count of BST by Bn for n elements
我们用n表示Bn的BST计数
The 2 subtrees here will be independent of each other. Therefore it will be ( B i-1 * B n-i ) for Bi . For n nodes (as i has n choices) it will be :
这里的2个子树将彼此独立。 因此,Bi将为(B i-1 * B ni)。 对于n个节点(因为我有n个选择),它将为:
Since the recurrence relation is same as of catalan numbers , so count of BST is given by Cn.
由于递归关系与加泰罗尼亚数相同,因此BST的计数由Cn给出。
Recurrence relation:
递归关系:
This gives complexity O(4^n). Complexity can be reduced to O(n^2) by using DP.
这给出了复杂度O(4 ^ n)。 使用DP可以将复杂度降低到O(n ^ 2)。
C++ implementation:
C ++实现:
#include <iostream>
using namespace std;
int CN(int n){
int Cn =0;
// base case
if(n==0) // empty tree
{
return 1;
}
for(int i=1;i<n+1;i++)
{
Cn+= CN(i-1)*CN(n-i);
}
return Cn;
}
int main(){
int n;
cout<<"Enter number of nodes: ";
cin>>n;
cout<<n<<endl;
int trees=CN(n);
cout<<trees<<" binary search trees are there for "<<n<<" nodes"<<endl;
return 0;
}
Output
输出量
Enter number of nodes: 4
14 binary search trees are there for 4 nodes
翻译自: https://www.includehelp.com/cpp-programs/find-number-of-bsts-with-n-nodes-catalan-numbers.aspx
bst 删除节点