二叉树的遍历
来源:互联网 发布:cf36 2检测到数据异常 编辑:程序博客网 时间:2024/06/01 19:35
#include<queue>#include<iostream> using namespace std; struct Tree{ int val; //结点数据 struct Tree *lchild; //左孩子 struct Tree *rchild; //右孩子 }; void addTree(Tree* T,Tree* p) //创造二叉树 { queue<Tree* >q;q.push(T);Tree * tem=q.front();while (!q.empty()){q.pop();if (tem->lchild==NULL){tem->lchild=p;break;}if (tem->rchild==NULL){tem->rchild=p;break;}q.push(tem->lchild);q.push(tem->rchild);tem=q.front();}} void front(Tree* T) //前序遍历 { if(T){ cout<<T->val<<" "; front(T->lchild); front(T->rchild); } } void middle(Tree* T) //中序遍历 { if(T){ middle(T->lchild); cout<<T->val<<" "; middle(T->rchild); } } void back(Tree* T) //后序遍历 { if(T){ back(T->lchild); back(T->rchild); cout<<T->val<<" "; } } void print(Tree* tree ) { if (!tree)return ;cout<<"按层打印:"<<endl;queue<Tree* >q;q.push(tree);while ( !q.empty() ){Tree * tem=q.front();q.pop();cout<<tem->val<<" ";if (tem->lchild!=NULL)q.push(tem->lchild);if (tem->rchild!=NULL)q.push(tem->rchild);}cout<<endl;} void main() { Tree* tree=NULL;Tree* p;printf("请输入结点内容(以0作为结束标识,不读入):\n");int val; cin>>val; while(val!=0){ //判断输入 p=new Tree ;//创建新结点 p->val = val; p->lchild = NULL; p->rchild = NULL; if(tree==NULL) tree=p; else addTree(tree,p); cin>>val;//读入用户输入 } print(tree); cout<<"前序遍历:"<<endl; front(tree); cout<<"\n中序遍历:"<<endl; middle(tree); cout<<"\n后序遍历:"<<endl; back(tree); }
阅读全文
0 0
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 二叉树的遍历
- 封装模板
- 达人篇:1)简单易懂的质量管理-写在达人篇开篇
- 【区块链】TestRPC Runtime Error: out of gas
- hadoop中NameNode、DataNode、Secondary、NameNode、JobTracker TaskTracker介绍
- Qt下使用微软的TTS
- 二叉树的遍历
- 考研数学
- 按钮防抖(防止重复点击)
- MT 110 Advice of Cheque(s)通知支票情况
- ios-GADBannerView设置背景图片
- 序列会扩展知识
- MT 111 Request for Stop Payment of a Cheque请求止付支票
- 高位优先的字符串排序(c++ ASCII)
- C语言中自动获取当前时间和日期