c++ dfs solution


  • 1
    H
    class Solution {
    public:
        vector<vector<int>> ans;
        void dfs(TreeNode* root, int sum, vector<int> cur) {
            if(!root) return;
            cur.push_back(root->val);
            if(!root->left && !root->right && root->val == sum) {
                ans.push_back(cur);
                return;
            }
            dfs(root->left, sum - root->val, cur);
            dfs(root->right, sum - root->val, cur);
        }
        vector<vector<int>> pathSum(TreeNode* root, int sum) {
            if(!root) return ans;
            dfs(root, sum, vector<int> (0));
            return ans;
        }
    };
    

Log in to reply
 

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