c++实现---多行从上往下打印二叉树

题目描述:给定一颗二叉树,从左到右从上到下打印二叉树。要求是要按层换行。
方法:层次遍历打印二叉树,用队列实现。本题是上一篇的变形,区别就是这个需要考虑到层数。
首先复习一下模板:
如果不需要确定当前遍历到了哪一层,模板如下:

void bfs() {
    vis[] = 0;
    queue<int> pq(start_val);

    while (!pq.empty()) {
        int cur = pq.front(); pq.pop();
        for (遍历cur所有的相邻节点nex) {
            if (nex节点有效 && vis[nex]==0){
                vis[nex] = 1;
                pq.push(nex)
            }
        }
    }
}

如果需要确定遍历到哪一层,模板如下;


```cpp
void bfs() {
 int level = 0;
 vis[] = {0}; // or set
 queue<int> pq(original_val);
 while (!pq.empty()) {
     int sz = pq.size();

     while (sz--) {
             int cur = pq.front(); pq.pop();
         for (遍历cur所有的相邻节点nex) {
             if (nex节点有效 && vis[nex] == 0) {
                 vis[nex] = 1;
                 pq.push(nex)
             }
         } // end for
     } // end inner while
     level++;

 } // end outer while
}

本题代码:


class Solution {
public:
        vector<vector<int> > Print(TreeNode* pRoot) {
            vector<vector<int>> res;
            if(!pRoot) return res;
            queue<TreeNode*> help;
            help.push(pRoot);//根节点入队列
            while(!help.empty()){
                int sz=help.size();
                vector<int> ans;
                while(sz--){
                    TreeNode * node=help.front();//先保存队列头节点
                    help.pop();//队首元素出队列
                    ans.push_back(node->val);//出队列的元素压入vector
                    if(node->left) help.push(node->left);//将出队列元素的非空左右子节点入队列
                    if(node->right) help.push(node->right);
                }
                res.push_back(ans);//将一个容器压入到另一个容器,实现多行打印
            }
        return res;
        }
};
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值