二叉树实验
来源:互联网 发布:mongodb ubuntu 编辑:程序博客网 时间:2024/05/16 05:26
#include <iostream>#include <cstdio>#include <cstdlib>#include <cstring>#include <stack>#include <queue>using namespace std;/**/#define ElemType chartypedef struct BiNode{ ElemType data; struct BiNode *lchild,*rchild;}BiNode,*BiTree;void creatBiTree(BiTree &T){ char c; cin>>c; if('#'==c) T=NULL; else { T=new BiNode; T->data=c; creatBiTree(T->lchild); creatBiTree(T->rchild); }}int preorder1(BiTree T){ stack<BiTree>s; s.push(T);//入栈。 while(!s.empty()) { BiTree u=s.top(); cout<<u->data<<" "; s.pop(); if(u->rchild!=NULL) s.push(u->rchild); if(u->lchild!=NULL) s.push(u->lchild); }}int midorder1(BiTree T){ stack<BiTree>S; BiTree p = T; while(p || !S.empty()) { while(p) { S.push(p); p = p->lchild; }//while结束意味着lson为空 if(!S.empty()) { cout<<S.top()->data<<' '; p = S.top()->rchild; S.pop(); } }}int preorder(BiTree T){ if(T) { cout<<T->data<<" "; preorder(T->lchild); preorder(T->rchild); }}int midorder(BiTree T){ if(T) { midorder(T->lchild); cout<<T->data<<" "; midorder(T->rchild); } return 0;}int postorder(BiTree T){ if(T) { postorder(T->lchild); postorder(T->rchild); cout<<T->data<<" "; } return 0;}int count(BiTree s){ if(!s) return 0; if(!s->rchild&&!s->lchild) return 1; return count(s->rchild)+count(s->lchild);}int getheight(BiTree s){ if(s) { int r=getheight(s->rchild); int l=getheight(s->lchild); return (r>l?r:l)+1; } return 0;}int ranks(BiTree T){ BiTree p = T; if(p) { queue<BiTree>Q; Q.push(p); while(!Q.empty()) { p = Q.front(); cout<<p->data<<' '; Q.pop(); if(p->lchild) Q.push(p->lchild); if(p->rchild) Q.push(p->rchild); } } return 0;}int main(){ BiTree T; std::ios::sync_with_stdio(false); //cie::tie(0); cout<<"请按照二叉树的格式输入"<<endl; creatBiTree(T); cout<<endl; cout<<"二叉树先序遍历(递归)"<<endl; preorder(T);cout<<endl; cout<<"二叉树中序遍历(递归)"<<endl; midorder(T);cout<<endl; cout<<"二叉树后序遍历(递归)"<<endl; postorder(T);cout<<endl; cout<<"二叉树先序遍历非递归版本"<<endl; preorder1(T);cout<<endl; cout<<"二叉树中序遍历非递归版本"<<endl; midorder1(T);cout<<endl; cout<<"本树的叶子数量"<<endl; cout<<count(T)<<endl; cout<<"天有多高??"<<endl; cout<<getheight(T)<<endl; cout<<"层次遍历"<<endl; cout<<ranks(T)<<endl; return 0;}
阅读全文
0 0
- 二叉树实验
- 二叉树实验代码
- 二叉树实验
- 二叉树实验报告
- 二叉树实验
- 实验五 二叉树
- 二叉树实验
- 二叉树实验5
- 二叉树实现实验
- 实验报告 二叉树
- 实验7-二叉树
- 二叉树实验
- 二叉树实验报告
- 实验三 二叉树
- 实验五: 树和二叉树实验
- 实验五: 树和二叉树实验
- 实验五:树和二叉树实验
- 实验五: 树和二叉树实验
- Spring Cloud Sleuth消息追踪测试
- C#极简方式实现枚举器的例子
- 移动端常见布局注意事项及解决方法
- lvs配置脚本
- tensorflow_cookbook:Ch 1: Getting Started with TensorFlow(8)08_Additional_Resources
- 二叉树实验
- BP算法推导(python实现)
- 浅谈WEB跨域的实现(前端向)
- AVL树
- 方法的传参
- 从柯洁对战AlphaGo,看商业智能
- 玩转大数据_顺利渡过34岁裁退危机!
- 文件路径中的/,\和\\的区别
- 概率分布-beta分布