题解 | #二叉树中和为某一值的路径(三)#
二叉树中和为某一值的路径(三)
https://www.nowcoder.com/practice/965fef32cae14a17a8e86c76ffe3131f
/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
     // 每个节点都充当单独的树来遍历一次
    int FindPath(TreeNode* root, int sum) {
        if (root == nullptr) return ans;
        dfs(root, sum);
        FindPath(root->left, sum);
        FindPath(root->right, sum);
        return ans;
    }
    // dfs 查询以某个节点为根的路径条数有多少
    void dfs(TreeNode* root, int sum) {
        if (root == nullptr) return;
        if (sum == root->val) ans++;
        dfs(root->left, sum - root->val);
        dfs(root->right, sum - root->val);
    }
private:
    int ans = 0;
};
2023-剑指-二叉树 文章被收录于专栏
 2023-剑指-二叉树
查看7道真题和解析
海康威视公司福利 1139人发布