二叉搜索树
2016-04-30 18:33
274 查看
递归的实质,就是当进入下一次递归是,数学模型仍然不变,只是范围减小。
以下代码主要运用尾递归。
即返回指针。
以下代码主要运用尾递归。
即返回指针。
//测试样例: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; }
相关文章推荐
- IO学习(六)拷贝文件夹
- IOS错误之----通过XCode上传App应用程序出现证书签名错误的解决方法
- C#碎碎念(二)快进一波
- 【Python】什么是闭包
- 讲义三 Applet
- HDU - 1874 畅通工程续(Dijkstra)
- 【Python】高阶函数介绍
- Python break和continue
- leetcode——103——Binary Tree Zigzag Level Order Traversal
- php判断图片的格式
- POJ3349_Snowflakes
- HDU 5672 String(尺取法)
- C语言之内存字节对齐
- Linux如何卸载正在执行的挂载文件
- Chrome 插件 Momentum 介绍
- HDU - 3790 最短路径问题(Dijkstra)
- Spring中的AOP(七)(实际上应该是一)——AspectJ的基本使用
- 语素
- TCP与UDP的区别
- Centos中查看nginx、apache、php、mysql配置文件路径