LeetCode-107: binary tree hierarchy traversal II

One, Title Description

  • Given a binary tree, the node returns its bottom-up value hierarchy traversal. (Ie, by physical layer to the layer from the leaf nodes of the root node, layer by layer traversal from left to right)

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

    3
   / \
  9  20
    /  \
   15   7

Returns to its bottom-up hierarchy traversal is:

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

Second, problem-solving approach

This is a series of problems. Binary tree traversal is common hierarchically, to separate the elements of each area.
The core step is how you determine the last element in each of which
we can use queue-level binary tree traversal, attention each time to re-enter whilethe cycle, queue data is binary current number of this layer node . Then we take a auto len = queue.size(), before the lendata is added vectoron it.

Third, the complete code

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        queue<TreeNode*> Q;
        vector<int> tmp;
        vector<vector<int>> sln;
        if(!root)   return sln;
        Q.push(root);
        while(!Q.empty()){
            auto size = Q.size();
            for(int i = 0; i < size; i++){
                auto ins = Q.front();
                Q.pop();
                tmp.push_back(ins->val);
                if(ins->left)
                    Q.push(ins->left);
                if(ins->right)
                    Q.push(ins->right);
            }
            sln.push_back(tmp);
            tmp.clear();
        }
        reverse(sln.begin(), sln.end());
        return sln;
    }
};

Fourth, operating results

Here Insert Picture Description

Published 30 original articles · won praise 3 · Views 824

Guess you like

Origin blog.csdn.net/weixin_44587168/article/details/105275533