二叉排序树(查找树)

时限:1000ms 内存限制:10000K  总时限:3000ms

描述:

已知二叉排序树中结点数据域为整数,根据键盘输入不同个数的数据构造二叉排序树,设计递归算法输出树中所有大于或等于给定值x的结点,并以函数的参数返回输出的结点个数并打印。假设以二叉链表为存储结构,其结点结构为: lchild data rchild

输入:

先输入数据的个数n,然后连续的n行每行一个正整数表示结点的值,最后输入正整数x。

输出:

先序输出树中所有大于或等于给定值x的结点的值和这样的结点的个数,每个数据占一行。

输入样例:

4

2

7

9

4

7

输出样例:

7

9

2

#include<iostream>
using namespace std;
typedef int datatype;
struct node
{
    datatype data;
    struct node *lchild,*rchild;
};
typedef struct node   BSnode;
typedef BSnode*       BSp;
int n,count=0,k,countprint=0;

BSp creatbstree(BSp Root);
void insertbstree(BSp *B,datatype key);
void inordersearch(BSp father);
int main()
{
    BSp Root=NULL;
    cin>>n;
    Root=creatbstree(Root);
    inordersearch(Root);
    cout<<countprint<<endl;
    return 0;
}
BSp creatbstree(BSp Root)
{
    datatype key;
    cin>>key;  count++;
    while(count<=n)
    {
        insertbstree(&Root,key);
        if(count==n)  { cin>>k; count++; }//输入截取点
        else   { cin>>key; count++; }
    }
    return Root;
}
void insertbstree(BSp *B,datatype x)
{
    BSp father,p,q;
    q=(struct node*)malloc(sizeof(struct node));//新建插入节点
    q->data=x;   q->lchild=NULL;   q->rchild=NULL;
    if(*B==NULL)   *B=q;//若根节点为NULL,则置插入节点为根节点    
    else
    {
        p=*B;//一开始将根节点置为子节点p
        while(p!=NULL)
        {
            father=p;//存储p的父节点
            if(x <p->data)  p=p->lchild;
            else  p=p->rchild;
        }//最后p=NULL,father!=NULL//找到插入位置father
        if(x <father->data)   father->lchild=q;
        else     father->rchild=q;
    }
}
void inordersearch(BSp father)
{
   if(father!=NULL)
   {  
       if(father->data >=k) 
       { cout<<father->data<<endl;  countprint++; } 
       inordersearch(father->lchild);
       inordersearch(father->rchild);
   }
}
原文地址:https://www.cnblogs.com/IThaitian/p/2585790.html