Print binary tree branches from the top down

Printing the binary tree in layers from top to bottom, from left to right to print the same node layer, each layer printed on one line.

Sample

输入如下图所示二叉树[8, 12, 2, null, null, 6, null, 4, null, null, null]
    8
   / \
  12  2
     /
    6
   /
  4

输出:[[8], [12, 2], [6], [4]]
/**
 * 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;
        if(!root) return res;
        
        queue<TreeNode*> q;
        q.push(root);
        q.push(nullptr);
        
        vector<int> level;
        
        while(q.size()){
            auto t = q.front();
            q.pop();
            
            if(!t){
                if(level.empty()) break;
                res.push_back(level);
                level.clear();
                q.push(nullptr);
                continue;
            }
            
            level.push_back(t->val);
            if(t->left) q.push(t->left);
            if(t->right) q.push(t->right);
        }
        
        return res;
    }
};
Published 79 original articles · won praise 0 · Views 591

Guess you like

Origin blog.csdn.net/weixin_44356316/article/details/103642961