437. 路径总和 III

给定一个二叉树,它的每个结点都存放着一个整数值。

找出路径和等于给定数值的路径总数。

路径不需要从根节点开始,也不需要在叶子节点结束,但是路径方向必须是向下的(只能从父节点到子节点)。

二叉树不超过1000个节点,且节点数值范围是 [-1000000,1000000] 的整数。

示例:

root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8

      10
     /  \
    5   -3
   / \    \
  3   2   11
 / \   \
3  -2   1

返回 3。和等于 8 的路径有:

1.  5 -> 3
2.  5 -> 2 -> 1
3.  -3 -> 11

分析:题目要求在以root为根结点的二叉树中,寻找和为sum的路径,返回这样的路径个数。
我们可以分两种情况进行递归遍历,

  • 第一种sum包含当前结点,在他的左右子树里面寻找和为sum的路径数量。递归调用dfs
  • 第二种,当前结点不包含在sum里面,直接调用pathSum递归
/**
 * 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:
    int pathSum(TreeNode* root, int sum) {
        if(root == NULL) {
            return 0;
        }
        int res = 0;
        res += dfs(root, sum);
        res += pathSum(root->left, sum);
        res += pathSum(root->right, sum);
        return res;
    }
private:
    int dfs(TreeNode* root, int num) {
        if(root == NULL) {
            return 0;
        }
        int res = 0;
        if(root->val == num) {
            res += 1;
        }
        res += dfs(root->left, num - root->val);
        res += dfs(root->right, num - root->val);
        return res;
    }
};

猜你喜欢

转载自blog.csdn.net/hy971216/article/details/81156570