Swust OJ1011: 二叉排序树的实现和查找

Knowledge:

 

#include<iostream>
using namespace std;
int flag;
typedef struct node
{
    int data;
    struct node *lchild,*rchild;
}Tree;

void CreateHead(Tree *&root)
{
    root=new Tree;
    cin>>root->data;
    root->lchild=root->rchild=NULL;
}//输入根结点的值

void CreateTree(Tree *&root,int k)//k为数据元素 
//创建二叉排序树
{
    if(root==NULL)//当根结点为空时 
    {
        root=new Tree;
        root->data=k;
        root->lchild=root->rchild=NULL;
        return ; 
     } 
else     if(root->data>k)//输入的数据元素比根结点小
     {
             CreateTree(root->lchild,k);//存储到左子树
     }
else    if(root->data<k)//输入数据元素比根结点大 
        {
                CreateTree(root->rchild,k);//存储到右子树
        }
             
}

void Searchkey(Tree *root,int key,int count)
//key表示要查找的元素,count表示计数
{
    if(root==NULL)//当结点为空,返回 
    {
        return ;
    }
    if(key==root->data)//当根结点值等于要查找的值
    {
        cout<<count;
        flag=1;
        return ;//找到了,输出计数次数
                 //flag赋值为1 
    } 
    else if(key<root->data)
    //当key小于根结点,到左子树
    {
        Searchkey(root->lchild,key,count+1); 
    } 
    else if(key>root->data)
    //当key大于根结点,到右子树
    {
        Searchkey(root->rchild,key,count+1); 
    } 
 } 
int main()
{
    int n;
    cin>>n;//元素个数
    int i;
    int count=1;
    Tree *root;
    CreateHead(root);
    int k;
    for(i=2;i<=n;i++)//因为在CreateHead中已输入一个元素 
    {    
        cin>>k;
        CreateTree(root,k);
     } //创建二叉排序树 
     flag=0;//初始化为0 
     int key;
     cin>>key;
     Searchkey(root,key,count);
     if(flag==0)
            cout<<"-1";
     return 0; 
}

 

猜你喜欢

转载自www.cnblogs.com/army613bts/p/12699488.html