113. 路径总和 II dfs 二叉树

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:
给定如下二叉树,以及目标和 sum = 22,

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/path-sum-ii
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

回忆dfs是怎么用的,若有两次dfs,应该在第一次之前加路径点,在第二次之后减路径点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector <int> path;
    vector <vector<int>> res;

    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        dfs(root, sum);
        return res;
    }

    void dfs(TreeNode* root, int sum) {
        if (root == nullptr) {
            return;
        }

        path.push_back(root->val);
        sum -= root->val;

        if (sum == 0 && root->left == nullptr && root->right == nullptr) {
            res.push_back(path);
        }
        
        dfs(root->left, sum);
        dfs(root->right, sum);

        path.pop_back();
    }
};
原文地址:https://www.cnblogs.com/xgbt/p/13737228.html