Recursive dfs c++ code


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

Log in to reply
 

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