107. Binary tree level traversal II C++

Topic: Given a binary tree, return the bottom-up level traversal of its node value. (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)

/**
 * 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;
        queue<TreeNode*>q1;
        if(root)
            q1.push(root);

        while(!q1.empty())
        {
    
    
            int len=q1.size();
            vector<int>v1;

            for(int i=0;i<len;++i)
            {
    
    
                TreeNode* node = q1.front();
                v1.push_back(node->val);
                if(node->left)
                    q1.push(node->left);
                if(node->right)
                    q1.push(node->right);
                q1.pop();
            }
            //result.insert(result.begin(),v1);//法1.头插
            result.push_back(v1);
        }
        reverse(result.begin(),result.end());//法2.反转数组
        return result;
    }
};

Guess you like

Origin blog.csdn.net/qq_41363459/article/details/113096498