二叉树的建立和基础操作<三> —— (三种遍历及分层打印)
2016-07-18 21:57
357 查看
#include<iostream> #include<vector> #include<queue> #include<math.h> #include<string.h> #include<algorithm> using namespace std; typedef struct BinaryTree { char val; struct BinaryTree *left; struct BinaryTree *right; }BinaryTree,*BitTree; //******递归建立二叉树*****// //先建立根节点,再建立左子树,最后建立右子树 /*********** 测试用例: a b c # d # e f # # # # # 输入:ab#df###c#e## ***************/ int create_tree(BitTree &T) { char val = getchar(); if(val == '#') T = NULL; else { T = new BinaryTree; T -> val = val; create_tree(T->left); create_tree(T->right); } return 0; } //*****前序递归遍历二叉树*****// void Preorder(BitTree T) { if(T) { cout<<T->val<<" "; Preorder(T->left); Preorder(T->right); } } //*****中序递归遍历二叉树*****// void Midorder(BitTree T) { if(T) { Midorder(T->left); cout<<T->val<<" "; Midorder(T->right); } } //*****后序递归遍历二叉树*****// void behindorder(BitTree T) { if(T) { behindorder(T->left); behindorder(T->right); cout<<T->val<<" "; } } //*****按层遍历*****// //设置游标last,分层打印二叉树 int layerorder_1(BitTree T) { vector<BitTree> vec; vec.push_back(T); int cur = 0; int last = 1; while(cur < vec.size()) { last = vec.size();//设置last游标 while(cur < last) //当last == cur时,退出循环,打印回车 { cout<<vec[cur]->val<<" "; if(vec[cur]->left) vec.push_back(vec[cur]->left); if(vec[cur]->right) vec.push_back(vec[cur]->right); cur++; } cout<<endl; } return 0; } //改写BFS,分层打印二叉树 int layerorder_2(BitTree T) { int parentSize = 1, childSize = 0; BitTree temp; queue<BitTree > q; q.push(T); do{ temp = q.front(); cout<<temp->val<<" "; q.pop(); parentSize--; //每次pop一个节点,parentSize减去1 if(temp->left) { q.push(temp->left); childSize++; } if(temp->right) { q.push(temp->right); childSize++; } if(parentSize == 0) //当根节点出栈完毕时,表示本层可以输出回车了 { //此时更新下一层parentSize,将childSize写入 parentSize = childSize; //childSize 赋值为0 childSize = 0; cout<<endl; } }while(!q.empty()); return 0; } int main() { BitTree T; create_tree(T); cout<<"前序遍历结果(递归):"<<endl; Preorder(T); cout<<endl<<"中序遍历结果(递归):"<<endl; Midorder(T); cout<<endl<<"后序遍历结果(递归):"<<endl; behindorder(T); cout<<endl<<"层次遍历结果1:"<<endl; layerorder_1(T); cout<<endl<<"层次遍历结果2:"<<endl; layerorder_2(T); return 0; }
程序运行结果:
相关文章推荐
- install mysql 5.7 winx64 on windows x64 server
- faster rcnn源码解读(六)之minibatch
- 伪类&伪元素
- Python的多版本如何处理--请使用pyenv
- 实现string的构造函数,析构函数,拷贝构造函数
- js表单克隆
- HTML5地理位置Geolocation以及百度地图应用
- Linux bash shell中变量的设置和使用
- 22.协议
- 优秀开源前端框架
- HDU 1596 find the safest road
- MongoDB学习笔记(索引)
- 关于LCA(Tarjan+ST)
- 会话管理之Session
- 利用Eclipse集成开发环境进行ROS开发
- 【Arduino官方教程】数字处理示例(五):按键状态变化检测
- discuz 可以使用多种缓存
- Python之检查URL
- window python 操作mysql、redis
- 深入阅读gulp源码小结