二叉搜索树

来源:互联网 发布:linux启动网卡命令 编辑:程序博客网 时间:2024/05/17 02:50

递归的实质,就是当进入下一次递归是,数学模型仍然不变,只是范围减小。

以下代码主要运用尾递归。

即返回指针。

//测试样例:30 15 41 50 33 35 34 0//二叉搜索树#include<iostream>#include<cstdio>#include<queue>using namespace std;typedef int Elemtype;typedef struct node{    Elemtype data;    struct node *lchild;    struct node *rchild;}BitTree;//后序遍历void PostOrder(BitTree *BST){    if(BST)    {        PostOrder(BST->lchild);        PostOrder(BST->rchild);        printf("%3d",BST->data);    }}//层次遍历void levelorder(BitTree *BST){    queue<BitTree*> s;    if(BST) s.push(BST);    BitTree *p;    while(!s.empty())    {        p=s.front();        s.pop();        printf("%3d",p->data);        if(p->lchild) s.push(p->lchild);        if(p->rchild) s.push(p->rchild);    }}//递归查找BitTree *Find(BitTree *BST,Elemtype x){    if(!BST) return NULL;    if(BST->data>x)        return Find(BST->lchild,x);    else if(BST->data<x)        return Find(BST->rchild,x);    else return BST;}//非递归查找BitTree *IterFind(BitTree *BST,Elemtype x){    while(BST)    {        if(BST->data>x)            BST=BST->lchild;        else if(BST->data<x)            BST=BST->rchild;        else return BST;    }    return NULL;}//递归查找最小元素BitTree *Findmin(BitTree *BST){    if(!BST) return NULL;    if(BST->lchild==NULL) return BST;    else return Findmin(BST->lchild);}//迭代查找最大元素BitTree *Findmax(BitTree *BST){    if(BST)        while(BST->rchild) BST=BST->rchild;    return BST;}//插入元素BitTree *Insert(BitTree *BST,Elemtype x){    if(!BST)    {        BST=(BitTree *)malloc(sizeof(BitTree));        BST->data=x;        BST->lchild=BST->rchild=NULL;    }    else{        if(x>BST->data)            BST->rchild=Insert(BST->rchild,x);        else if(x<BST->data)            BST->lchild=Insert(BST->lchild,x);    }    return BST;}//删除元素BitTree *Delete(Elemtype m,BitTree *BST){    BitTree *Tmp;    if(!BST) printf("Not find\n");    else if(BST->data>m)        BST->lchild=Delete(m,BST->lchild);    else if(BST->data<m)        BST->rchild=Delete(m,BST->rchild);    else        if(BST->lchild&&BST->rchild)        {            Tmp=Findmax(BST->rchild);            BST->data=Tmp->data;            BST->rchild=Delete(Tmp->data,BST->rchild);        }        else{            Tmp=BST;            if(!BST->lchild)                BST=BST->rchild;            else if(!BST->rchild)                BST=BST->lchild;            free(Tmp);        }    return BST;}int main(){    Elemtype x;    Elemtype y;    BitTree *min,*max,*f;    BitTree *BST = nullptr;    while(cin>>x&&x)        BST=Insert(BST, x);    scanf("%d",&y);    f=Find(BST, y);    min=Findmin(BST);    max=Findmax(BST);    levelorder(BST);    cout<<endl;    printf("%3d",f->data);    printf("%3d",min->data);    printf("%3d",max->data);    printf("\n");    int m;    scanf("%d",&m);    Delete(m,BST);    levelorder(BST);    cout<<endl;    return 0;}


0 0
原创粉丝点击