DFS c++ solution beats 93%


  • 0
    M

    class Solution {
    public:

    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> result;
        vector<int> set;
        int res = 0;
        if(!root) return result;
        dfs(root,result,set,res,sum);
        return result;
    }
    
    void dfs(TreeNode* root,vector<vector<int>>& result,vector<int>& set,int& res,int sum){
        
        if(!root) return;
        set.push_back(root->val);
        res += root->val;
       // if(res > sum) return;
        if(!root->left && !root->right){
            if(res == sum)
            result.push_back(set);
            return;
        }
        if(root->left){
            dfs(root->left,result,set,res,sum);
            res -= set[set.size()-1];
            set.pop_back();
        }
        if(root->right){
            dfs(root->right,result,set,res,sum);
            res -= set[set.size()-1];
            set.pop_back();
        }
    }
    

    };


Log in to reply
 

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