欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

LeetCode 107. 二叉树的层次遍历 II(reverse一下即可)

程序员文章站 2022-05-20 20:25:06
...

二叉树的层次遍历 II

/**
 * 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>> ans;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty()){
            int size = q.size();
            vector<int> list;
            while(size--){
                TreeNode* r =  q.front();
                q.pop();
                if(!r){
                    continue;
                }
                list.push_back(r->val);
                q.push(r->left);
                q.push(r->right);
            }
            if(list.size()){
                ans.push_back(list);
            }
            
        }
        reverse(ans.begin(),ans.end());
        return ans;
    }
};