分层遍历二叉树
来源:互联网 发布:手机网页翻译软件 编辑:程序博客网 时间:2024/04/30 01:23
用map存储节点 <key ,value> key表示节点编号, value 是儿子,用pair实现。
遍历采用 bfs 、 优化在于 level 部分
#include<iostream>#include<sstream>#include<string>#include<map>#include<queue>using namespace std;typedef pair<int,int> Son;typedef map<int,Son> Tree;void bfs(Tree t,int root){queue<int> Q;Q.push(root);int level = 1;while( !Q.empty() ) {cout<<"level:"<<level<<endl;level++;int numNode = Q.size();while( numNode-- ){int node = Q.front(); Q.pop();cout<<node<<" ";Tree::iterator pos = t.find(node);if (pos != t.end()){Son child = pos->second;if( child.first >0) Q.push( child.first );if( child.second>0) Q.push( child.second);}}cout<<endl;}}int main(){Tree t;int root;cout<<"root:";cin>>root;cin.get();string line;while( getline(cin,line) ){if (line == "0") break;stringstream str(line);int father;str>>father; cout<<father <<endl;int lchild, rchild;lchild = rchild = -1;str >> lchild >> rchild;cout<<lchild <<","<<rchild <<endl; if( lchild!=-1 || rchild!=-1)t[father] = Son(lchild,rchild); }bfs(t,root);system("pause");return 0; }
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 分层遍历二叉树
- 二叉树遍历、分层遍历
- 二叉树的分层遍历
- 带粉离港
- (译)碰撞检测和收集物品:如何使用cocos2d制作基于tiled地图的游戏:第二部分
- linux下使用jni实现c++调用java程序(2)找不到java类的问题
- ZJUT 1208 排列对称串
- (译)加入敌人和战斗:如果使用cocos2d制作基于tiled地图的游戏:第三部分
- 分层遍历二叉树
- Jfreechart柱形图详细设置(转)
- form表单字段元素对象实例(二)— —用户名和密码争夺焦点,造成死锁事件
- pku Graph Coloring
- 很有用的Html 显示特殊符号
- NSAssert
- Android软件安全开发实践(上)
- 优化C++游戏:对象的创建和销毁
- (译)如何使用cocos2d开发一个简单的iphone游戏:旋转炮塔。(第二部分)