二叉排序樹的基本騷操作

二叉排序樹的基本操作

#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);
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章