最常见的程序员面试题(2)逐层打印2叉树

    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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值