Sword refers to offer 44 branch to print the binary tree from top to bottom

Topic

Insert picture description here

answer

  1. For the layer order traversal of the binary tree, we can directly use the BFS priority queue, just like the previous question, but this question allows us to output hierarchically. Here is a little trick, we can add a nullptr after each layer
  1. 8 nullptr 12 2 nullptr 6 nullptr 4 nullptr, so that each traversal to nullptr is the end of a layer, see the code for details

Code

/**
 * 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;
    }
};

Guess you like

Origin blog.csdn.net/qq_44791484/article/details/115148094