描述
已知二叉排序树中结点数据域为整数,根据键盘输入不同个数的数据构造二叉排序树,设计递归算法输出树中所有大于或等于给定值x的结点,并以函数的参数返回输出的结点个数并打印。假设以二叉链表为存储结构,其结点结构为:
lchild data rchild
lchild data rchild
输入
先输入数据的个数n,然后连续的n行每行一个正整数表示结点的值,最后输入正整数x。
输出
先序输出树中所有大于或等于给定值x的结点的值和这样的结点的个数,每个数据占一行。
输入样例
4
2
7
9
4
7
2
7
9
4
7
输出样例
7
9
9
2
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
typedef struct Node
{
struct Node *lchild;
struct Node *rchild;
int data;
}Node, **PNode;
int cnt = 0;
void Create(PNode root, int temp)
{
if((*root) == NULL)
{
(*root) = (Node*)malloc(sizeof(Node));
(*root)->lchild = NULL;
(*root)->rchild = NULL;
(*root)->data = temp;
}
else if((*root)->data > temp)
{
Create(&(*root)->lchild, temp);
}
else if((*root)->data < temp)
{
Create(&(*root)->rchild, temp);
}
}
void traverse(Node* root , int aim)
{
if(root == NULL)
return;
if(root->data >= aim)
{
printf("%d\n", root->data);
cnt++;
}
traverse(root->lchild, aim);
traverse(root->rchild, aim);
}
int main()
{
int n;
cin >> n;
Node *root = NULL;
cnt = 0;
while(n--)
{
int temp;
cin >> temp;
Create(&root, temp);
}
int aim;
cin >> aim;
traverse(root, aim);
printf("%d\n", cnt);
return 0;
}