Leetcode107.二叉树的层次遍历||

时间:2020-09-06 14:38:23   收藏:0   阅读:48

题意

求二叉树的的层次遍历,但是是逆序的

思路

代码

class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        if(!root)   return {};
        vector<vector<int>> ans;
        queue<TreeNode*> q;
        q.push(root);
        while(!q.empty())
        {
            vector<int> tmp;
            int level_length = q.size();
            for(int i=0;i<level_length;i++)
            {
                auto cur = q.front();
                q.pop();
                tmp.emplace_back(cur->val);
                if(cur->left)   q.push(cur->left);
                if(cur->right)  q.push(cur->right);
            }
            ans.emplace_back(tmp);
        }
        reverse(ans.begin(), ans.end());		//逆置
        return ans;
    }
};

原文:https://www.cnblogs.com/MartinLwx/p/13621365.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!