使用C ++的给定高度的AVL树中的最小节点数。
问题陈述
给定AVL树的高度,任务是找到该树可以具有的最小节点数。
If height = 0 then AVL tree can have one 1 node If height = 5 then AVL tree can have minimum 20 nodes
算法
在AVL树中,我们必须保持高度平衡属性,即,每个子节点的左右子树的高度差不能超过-1、0或1。使用此属性,我们可以创建以下递归关系:
1. If height = 0 then return 1 2. If height = 1 then return 2 3. If height > 1 then return (1 + getMinAVLNodes(h – 1) + getMinAVLNodes(h – 2))
示例
#include <iostream>
using namespace std;
int getMinAVLNodes(int h){
if (h < 0) {
return 0;
}
if (h == 0 || h == 1) {
return h + 1;
}
return 1 + getMinAVLNodes(h - 1) + getMinAVLNodes(h -2);
}
int main(){
int h = 5;
cout << "Minimum nodes for " << h << " height = " << getMinAVLNodes(h) << endl;
return 0;
}输出结果
当您编译并执行上述程序时。它生成以下输出-
Minimum nodes for 5 height = 20
热门推荐
10 八一幼儿祝福语大全简短
11 公司乔迁食堂祝福语简短
12 婚礼结束聚餐祝福语简短
13 儿媳买车妈妈祝福语简短
14 毕业送礼老师祝福语简短
15 同事辞职正常祝福语简短
16 恭贺新婚文案祝福语简短
17 金店立秋祝福语简短英文
18 婆婆高寿祝福语大全简短