Dfs recursive solution without stack or queue


  • 0
    C
    class Solution {
    public:
        
        vector< vector<int> > result;
        
        void dfs(TreeNode *root, int level)
        {
            if(!root) return;
            
            if(level == result.size()) 
                result.push_back( vector<int>() );
            
            vector<int> &vec = result[level];
            vec.push_back(root->val);
            
            dfs(root->left, level+1);
            dfs(root->right, level+1);
        }
        
        vector<vector<int>> levelOrderBottom(TreeNode* root)
        {
            if(!root) return vector< vector<int> >();
            
            dfs(root, 0);
            
            return vector< vector<int> >(result.rbegin(), result.rend());
        }
    };

Log in to reply
 

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