2叉树的遍历有3种方式,但是哪一种都不是能逐层遍历2叉树的。因此这是一个广度优先的算法设计。想到广度优先,我们就知道必须引入一个额外的存储队列。那么算法就是这样: 从第一层开始,把根节点元素压入这个FIFO队列,开始循环。循环的过程可以描述为:
(1) 每次取出队首元素,打印其数据,然后把它的左右叶子的信息分别压入队列
(2) 从队首删除这个元素。
C++代码描述为:
#include <deque>
#include <cstdlib>
using namespace std;
struct node{
explicit node( int d )
: data( d ),
pLeft( nullptr ),
pRight( nullptr )
{}
~node(){
delete pLeft;
delete pRight;
}
int data;
node* pLeft;
node* pRight;
node* appendLeft( node* pn ){
if( pLeft )delete pLeft;
pLeft = pn;
return pLeft;
}
node* appendRight( node* pn ){
if( pRight )delete pRight;
pRight = pn;
return pRight;
}
};
void printLayers( node& n ){
std::deque<node*> di;
di.push_back(&n);
while(di.size()){
node* pn=di.front();
printf("%d,",pn->data);
if(pn->pLeft)
di.push_back(pn->pLeft);
if(pn->pRight)
di.push_back(pn->pRight);
di.pop_front();
}
}
int main(void){
node root(1);
node* r_left=root.appendLeft( new node(2) );
node* r_right=root.appendRight( new node(3) );
node* lr=r_left->appendRight( new node(5) );
node* ll=r_left->appendLeft( new node(4) );
node* rl=r_right->appendLeft( new node(6) );
node* rr=r_right->appendRight( new node(7) );
printLayers( root );
return 0;
}
这个2叉树的结构是:
1
| \
2 3
| \ | \
4 56 7
打印的结果是1,2,3,4,5,6,7