二叉查找树的基本操作

#include<bits/stdc++.h>

struct node{
    int data;
    node* lchild;
    node* rchild;
};

void search(node* root,int x){//查找二叉查找树中数据域为x的结点
    if(root==NULL){
        printf("search failed\n");
        return;
    }
    if(x==root->data){//查找成功,访问之
        printf("%d\n",root->data);
    }
    else if(x<root->data){//如果x比根节点的数据域小,说明x在左子树
        search(root->lchild,x);//向左子树搜索x
    }else{//x比根节点的数据域大,说明x在右子树
        search(root->rchild,x);//向右子树搜索x
    }
}

node* newNode(int v){//生成一个新结点,x为结点权值
    node* Node=new node;//申请一个node型变量的地址空间
    Node->data=v;
    Node->lchild=Node->rchild=NULL;//初始状态下没有左右孩子
    return Node;//返回新建结点的地址
}

void insert(node* &root,int x){//在二叉树中插入一个数据域为x的新结点
    if(root==NULL){//空树,说明查找失败,也即插入位置
        root=newNode(x);//新建结点,权值为x
        return;
    }
    if(x==root->data) return;
    else if(x<root->data){//x比根节点的数据域小时需要插在左子树
        insert(root->lchild,x);//往左子树搜索x
    }else{//x比根节点的数据域大时需要插在右子树
        insert(root->rchild,x);//往右子树搜索x
    }
}

node* Create(int data[],int n){
    node* root=NULL;//新建根节点root
    for(int i=0;i<n;i++){
        insert(root,data[i]);
    }
    return root;//返回根节点
}

node* findMax(node* root){
    while(root->rchild!=NULL) root=root->rchild;//不断往右,直到没有右孩子
    return root;
}

node* findMin(node* root){
    while(root->lchild!=NULL) root=root->lchild;//不断往左,直到没有左孩子
    return root;
}

void deleteNode(node* &root,int x){//删除以root为根节点的树种权值为x的结点
    if(root==NULL) return;//不存在权值为x的结点
    if(root->data==x){//找到欲删除的结点
        if(root->lchild==NULL&&root->rchild==NULL){//叶子结点直接删除
            root=NULL;
        }
        else if(root->lchild!=NULL){//左子树不为空时
            node* pre=findMax(root->lchild);//找root的前驱
            root->data=pre->data;
            deleteNode(root->lchild,pre->data);//在左子树种删除结点pre
        }
        else if(root->rchild!=NULL){
            node* next=findMin(root->rchild);//找root的后继
            root->data=next->data;//用后继覆盖root
            deleteNode(root->rchild,next->data);//在右子树种删除结点next
        }
    }
    else if(root->data>x){
        deleteNode(root->lchild,x);//在左子树种删除x
    }else{
        deleteNode(root->rchild,x);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值