Share my clear buy slow c++ solution


  • 0
    Z

    I use insert to add in the front of the vector.

    and use res.size()-level to find where the node should be in the res.

    but insert really takes a lot of time.

    In fact, it takes 70ms.

    vector<vector<int>> res;
    vector<int> tmp;
    
    void helper(TreeNode *curr,int level){
        if(curr==NULL)return;
        int s=res.size();
        
        if(level==s){
            res.insert(res.begin(),tmp);
            s++;            
        }
        
        level++;
        
        res[s-level].push_back(curr->val);
        
        helper(curr->left,level);
        helper(curr->right,level);
    }
    vector<vector<int> > levelOrderBottom(TreeNode *root) {
        helper(root,0);
        return res;
    }

Log in to reply
 

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