C++ recursive solution 8ms


  • 0
    T

    class Solution {
    public:
    void myLevelOrder(TreeNode* root, int level)
    {

        if(res.size()<=level) 
            res.push_back(vector<int>());
        res[level].push_back(root->val);
        if(root->left) myLevelOrder(root->left, level+1);
        if(root->right) myLevelOrder(root->right, level+1);
        
    }
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
       if(!root) return res;
       myLevelOrder(root, 0);
       reverse(res.begin(),res.end());
       return res;
        
    }
    

    private:
    vector<vector<int>> res;
    };


  • 0
    L

    Why do we need:

    if(res.size()<=level) 
        res.push_back(vector<int>());
    

    Im trying to understand the solution.


Log in to reply
 

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