最新消息:热烈庆祝IT小记上线!

leetcode 刷刷刷

https://leetcode.com/problems/binary-tree-level-order-traversal-ii/

class Solution {
    
    
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int> >ret;
        
        queue<TreeNode*> Q1;
        queue<int> Q2;
        if(root){
            Q1.push(root);
            Q2.push(1);
        }
        int lastlevel = 0;
        while(!Q1.empty()){
            TreeNode * r = Q1.front(); Q1.pop();
            int level = Q2.front();Q2.pop();
            printf("%d\n", level);
            if(level!=lastlevel){
                vector<int> tmp;
                tmp.push_back(r->val);
                ret.insert(ret.begin(), tmp);
            }
            else{
                ret[0].push_back(r->val);
            }
            lastlevel = level;
            if(r->left){
                Q1.push(r->left);
                Q2.push(level+1);
            }
            if(r->right){
                Q1.push(r->right);
                Q2.push(level+1);
            }
        }
        return ret;
    }
};


猜您喜欢

备案号:苏ICP备12016861号-4