二叉搜索树的搜索(ALDS1_8_B:Binary tree II)

以根为结点调用find,从根向叶搜索结点。如果给定键值小于当前结点x的键值,那么搜索目标移动至左子结点继续搜索,反之移动至右子节点,键值不存在时返回NIL

node *find(node *u,int k)
{
    while(u!=NIL&&k!=u->key){
        if(k<u->key){
            u=u->left;
        }else{
            u=u->right;
        }
    }
    return u;
}
#include<iostream>
#include<cstdio>
#include<string>
#include<cstdlib>

using namespace std;

struct node{
    int key;
    node *right,*left,*parent;
};

node *root,*NIL;

void insert(int k)
{
    node *y=NIL;
    node *x=root;
    node *z;

    z=(node*)malloc(sizeof(node));
    z->key=k;
    z->left=NULL;
    z->right=NULL;

    while(x!=NULL){
        y=x;
        if(z->key<x->key){
            x=x->left;
        }else{
            x=x->right;
        }
    }

    z->parent=y;

    if(y==NIL){
        root=z;
    }else{
        if(z->key<y->key){
            y->left=z;
        }else{
            y->right=z;
        }
    }
}

void inorder(node *u)
{
    if(u==NULL){
        return ;
    }
    inorder(u->left);
    printf(" %d",u->key);
    inorder(u->right);
}

void preorder(node *u)
{
    if(u==NULL){
        return ;
    }
    printf(" %d",u->key);
    preorder(u->left);
    preorder(u->right);
}

node *find(node *u,int k)
{
    while(u!=NIL&&k!=u->key){
        if(k<u->key){
            u=u->left;
        }else{
            u=u->right;
        }
    }
    return u;
}

int main()
{
    int n,k;
    string com;
    scanf("%d",&n);
    for(int i=0;i<n;i++){
        cin>>com;
        if(com=="insert"){
            scanf("%d",&k);
            insert(k);
        }else if(com=="print"){
            inorder(root);
            printf("\n");
            preorder(root);
            printf("\n");
        }else{
            scanf("%d",&k);
            node *t=find(root,k);
            if(t!=NULL){
                printf("yes\n");
            }else{
                printf("no\n");
            }
        }
    }
    return 0;
}
/*
10
insert 30
insert 88
insert 12
insert 1
insert 20
insert 17
insert 25
find 16
print
*/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值