剑指 offer 44 分行从上往下打印二叉树

题面

在这里插入图片描述

题解

  1. 对于二叉树的层序遍历,我们直接用BFS优先队列即可,像上一题一样,但是这题让我们分层输出,这里有一个小技巧,我们可以在每层后边加一个nullptr
  1. 8 nullptr 12 2 nullptr 6 nullptr 4 nullptr ,这样每次遍历到nullptr 都是一层结尾,具体看代码

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
    
    
public:
    vector<vector<int>> printFromTopToBottom(TreeNode *root) {
    
    
        vector<vector<int>> res;
        vector<int> cur;
        if (!root) return res;
        queue<TreeNode *> q;
        q.push(root);
        q.push(nullptr);
        while (q.size()) {
    
    
            auto t = q.front();
            q.pop();
            if (t) {
    
    
                cur.push_back(t->val);
                if (t->left) q.push(t->left);
                if (t->right) q.push(t->right);
            } else {
    
     //说明已经遍历完这个层
                res.push_back(cur);
                cur.clear();
                if(q.size()) q.push(nullptr);
            }
        }
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/qq_44791484/article/details/115148094