bst 删除节点_C ++程序查找具有N个节点的BST数量(加泰罗尼亚编号)

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的计数:

catalan-number

For n=0 number of trees is 1 i.e. empty tree. For subsequent values:

对于n = 0 ,树的数量为1,即空树。 对于后续值:

catalan-number

And, so on...

等等...

Solution:

解:

If we consider root as the ith node then:

如果我们将root视为第i 节点,则:

  1. i-1 nodes are there in left subtree.

    i-1节点在左子树中。

  2. 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个选择),它将为:

catalan-number

Since the recurrence relation is same as of catalan numbers , so count of BST is given by Cn.

由于递归关系与加泰罗尼亚数相同,因此BST的计数由Cn给出。

Recurrence relation:

递归关系:

catalan-number

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 删除节点

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值