Simple c++ dfs solution

  • 0
    void dfs(vector<vector<int>>& res, vector<int>& cur, TreeNode* root, int curSum, int target) {
        if (target == curSum && !root->left && !root->right) res.push_back(cur);
        if (root->left) dfs(res, cur, root->left, curSum + root->left->val, target);
        if (root->right) dfs(res, cur, root->right, curSum + root->right->val, target);
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> res;
        vector<int> cur;
        if (!root) return res;
        dfs(res, cur, root, root->val, sum);
        return res;

Log in to reply

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