Rehearsal-Leetcode-107. Sequence Traversal of Binary Tree II

107. Sequence Traversal of Binary Tree II

Topic link

Source: LeetCode
Link: https://leetcode-cn.com/problems/binary-tree-level-order-traversal-ii/

Title description

Given a binary tree, return the bottom-up traversal of its node values. (That is, from the layer where the leaf node is located to the layer where the root node is located, traverse from left to right layer by layer)

For example:
Given a binary tree [3,9,20,null,null,15,7],

3

/
920
/
157
returns to its bottom-up traversal of the sequence:

[
[15,7],
[9,20],
[3]
]

Topic analysis

Very similar to the 102 question

/**
 * 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>> levelOrderBottom(TreeNode* root) {
    
    
        vector<vector<int>> result;
        if(root == nullptr){
    
    
            return result;
        }
        queue<TreeNode*> queue;
        queue.push(root);
        int n;//存放每层节点数
        while(!queue.empty()){
    
      
            vector<int> tmp;
            n = queue.size();
            while(n--){
    
    
                root = queue.front();//注意放while里面
                if(root->left) queue.push(root->left);
                if(root->right) queue.push(root->right);
                tmp.push_back(root->val);
                queue.pop();
            }
            result.push_back(tmp);
        }
        reverse(result.begin(),result.end());
        return result;
    }
};

Guess you like

Origin blog.csdn.net/qq_42771487/article/details/113689600