【问题描述】
使用先序遍历序列建立链式存储结构的二叉树,输入一个n,求出二叉树的右子树中大于n的结点数量。
【输入形式】
按先序遍历序列输入二叉树的结点信息;输入一个值n。(结点的数值为正整数,0表示空)
【输出形式】
输出右子树中大于n的结点的数量。
【样例输入】
19 6 8 0 0 45 0 0 20 33 0 0 1 0 0
18
【样例输出】
2
代码部分
由于前几篇博文二叉树的创建都是用指针传参来实现的,本篇二叉树的创建用引用传参来实现(C++引用很重要!)。
不得不说引用真的很好用,尤其涉及到二级指针、三级指针等多级指针传参时,可发挥把指针降级的作用(本例未体现此作用,实例请查看我的另一博文哈夫曼编码的创建部分–>点击此处跳转)。
#include<iostream>
using namespace std;
typedef struct tree {
int data;
tree* lchild;
tree* rchild;
};
void create(tree*& t) { //用引用传参
int temp = 0;
cin >> temp;
if (temp == 0) {
t = NULL;
return;
}
t = new tree;
t->data = temp;
create(t->lchild);
create(t->rchild);
return;
}
void count(tree* t, int& cnt,int n) {
if (t) {
if (t->data > n)
cnt++;
count(t->lchild, cnt, n);
count(t->rchild, cnt, n);
}
}
int main() {
tree* t;
create(t);
int cnt = 0, n = 0;
cin >> n;
count(t->rchild, cnt, n);
cout << cnt << endl;
return 0;
}