分层遍历二叉树

来源:互联网 发布:手机网页翻译软件 编辑:程序博客网 时间: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; }

原创粉丝点击