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的計數:
For n=0 number of trees is 1 i.e. empty tree. For subsequent values:
對于n = 0 ,樹的數量為1,即空樹。 對于后續值:
And, so on...
等等...
.minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}} .minHeight{min-height: 250px;}@media (min-width: 1025px){.minHeight{min-height: 90px;}}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 caseif(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 刪除節點
總結
以上是生活随笔為你收集整理的bst 删除节点_C ++程序查找具有N个节点的BST数量(加泰罗尼亚编号)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 颐和园免票人员怎么预约门票
- 下一篇: 信息安全主动攻击和被动攻击_信息安全中的