输入:待访问的二叉树Tree
输出:对节点的层序访问
View:
queue.push Tree
while !queue.empty:
if (Tree.left) queue.push Tree.left
if (Tree.right) queue.push Tree.right
Tree.show
queue.pop
Plain text
C++实现
#include<iostream>#include<queue>usingnamespace std;// 简单实现一个二叉树structTree{Tree():left(nullptr),data(0),right(nullptr){}
Tree *left;char data;
Tree *right;};// 层序遍历voidView(const Tree &T){
queue<Tree> nodeQueue;
nodeQueue.push(T);while(!nodeQueue.empty()){auto cur = nodeQueue.front();if(cur.left) nodeQueue.push(*cur.left);if(cur.right) nodeQueue.push(*cur.right);
nodeQueue.pop();
cout << cur.data;}
cout << endl;}