二叉排序树(BST)

基础详细请点击

#include<bits/stdc++.h>
using namespace std;
int arr[] = { 17,12,19,10,15,18,25,8,11,13,16,22};
typedef struct bst
{
    int data;
    struct bst *lc,*rc;
} bst,*BST;
BST Search(BST root,int key)
{
    BST p=root;
    while(p)
    {
        if(p->data==key)
        {
            return p;
        }
        p=(key< p->data)? p->lc:p->rc;
    }
    return NULL;
}
void Insert(BST &root,int data)
{
    BST p=new bst;
    p->data=data;
    p->lc=p->rc=NULL;
    if(root==NULL)
    {
        root=p;
        return;
    }
    if(Search(root,data))
        return;
    BST tnode=NULL,troot=root;
    while(troot)
    {
        tnode=troot;
        troot=(data< troot->data)?troot->lc:troot->rc;
    }
    if(data<tnode->data)
        tnode->lc=p;
    else
        tnode->rc=p;

}
void inorder(BST T)
{
    if(T)
    {
        inorder(T->lc);
        printf("%d ",T->data);
        inorder(T->rc);
    }
}
void Delete(BST &root,int data)
{
    BST p=root,parent=NULL,s=NULL;
    if(!p)
        return;
    if(data<p->data)
        Delete(p->lc,data);
    else if(data>p->data)
        Delete(p->rc,data);
    else
    {
        if(!p->lc&&!p->rc)
            root=NULL;
        else if(!p->lc&&p->rc)
            root=p->lc;
        else if(p->lc&&!p->rc)
            root=p->rc;
        else
        {
            s=p->rc;
            if(!s->lc)
                s->lc=p->lc;
            else
            {
                while(s->lc)
                {
                    parent=s;
                    s=s->lc;
                }
                parent->lc=s->rc;
                s->lc=p->lc;
                s->rc=p->rc;
            }
            root=s;
        }
        delete p;
    }
}
int main()
{
    BST root=NULL;
    for(int i=0; i<12; i++)
        Insert(root,arr[i]);
    inorder(root),printf("\n");
    BST result=Search(root,12);
    if(result)
        printf("yes\n");
    else printf("no\n");
    inorder(root),printf("\n");
    Insert(root,9);
    inorder(root),printf("\n");
    Delete(root,12);
    inorder(root),printf("\n");
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41061455/article/details/80261128