二叉排序树的基本骚操作

二叉排序树的基本操作

#include<bits/stdc++.h>
using namespace std;
struct BiTree{
    int data;
    struct BiTree *lchild,*rchild;
};
typedef BiTree*  node;
node search(int T,node root)//二叉排序树的搜索
{
    node h=new struct BiTree;
    h=root;
    while(h)
    {
        if(T<h->data){
            h=h->lchild;
        }
        else if(T>h->data){
            h=h->rchild;
        }
        else if(T==h->data){
            return h;
        }
    }
    return NULL;
}
node FindMax(node root)//寻找最大值
{
    node h=new struct BiTree;
    h=root;
    if(h){
        while(h->rchild) h=h->rchild;
    }
    return h;
}
node FindMin(node root)//寻找最小值
{
    node h=new struct BiTree;
    h=root;
    if(h){
        while(h->lchild) h=h->lchild;
    }
    return h;
}
node insert(int T,node root)//插入操作
{
    if(root==NULL){
        root=new struct BiTree;
        root->data=T;
        root->lchild=NULL;
        root->rchild=NULL;
    }
    else{
        if(T<root->data){
            root->lchild=insert(T,root->lchild);
        }
        else if(T>root->data){
            root->rchild=insert(T,root->rchild);
        }
    }
    return root;
}
node Delete(int T,node root)//删除指定值
{
    if(search(T,root)==NULL) cout<<"the value is not found"<<endl;
    else{
        if(T<root->data){
            root->lchild=Delete(T,root->lchild);

        }
        else if(T>root->data){
            root->rchild=Delete(T,root->rchild);
        }
        else if(T==root->data){
            if(root->lchild!=NULL&&root->rchild!=NULL){
                node temp=FindMin(root->rchild);
                root->data=temp->data;
                root->rchild=Delete(temp->data,root->rchild);
            }
            else{
                if(root->rchild==NULL&&root->lchild!=NULL){
                    root=root->lchild;
                }
                else if(root->rchild!=NULL&&root->lchild==NULL){
                    root=root->rchild;
                }
                else{
                    root=NULL;
                }
            }
        }
    }
    return root;
}
node create_a_tree(int n)
{
    node head=new struct BiTree;
    head=NULL;
    for(int i=0;i<n;i++){
        int a;cin>>a;
        head=insert(a,head);
    }
    return head;
}
void printt(node head)//中序遍历
{
    if(head){
        printt(head->lchild);
        cout<<head->data<<" ";
        printt(head->rchild);
    }
}
int main()
{
    int n;cin>>n;
    node root=create_a_tree(n);
    printt(root);
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值