Share my C++ solution 4ms


  • 0
    J

    class Solution {
    public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {

        vector<vector<int>> res;
        vector<int> level;
        TreeNode* node;
        
        if(root==NULL) return res;  //注意root为空的时候返回的类型也是res这种
        
        queue<TreeNode*> q;
        int currlev=1;
        int nextlev=0;
        
        q.push(root);
        while(!q.empty()){
            node=q.front();
            currlev--;
            q.pop();
            level.push_back(node->val);
            
            if(node->left){
                q.push(node->left);
                nextlev++;
            }
            if(node->right){
                q.push(node->right);
                nextlev++;
            }
            if(currlev==0){
                //res.insert(res.begin(),level);  这句话会让程序明显减慢
                res.push_back(level);
                currlev=nextlev;
                nextlev=0;
                level.clear();//level要清空
            }
        }
        reverse(res.begin(),res.end());  //这句话起了翻转作用
        return res;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.