leetcode 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

思路分析:

leetcode的easy题,但是做起来还是有点难度。。。

和之前从根开始找路径的题比起来,需要多判断以各个子结点为起点计算路径,递归实现。

代码:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int pathSumCore(TreeNode* root, int sum)
13     {
14         if(root == nullptr)
15             return 0;
16         int res=0;
17         if(root->val == sum)
18         {
19             res += 1;
20         }
21         res += pathSumCore(root->left, sum-root->val);
22         res += pathSumCore(root->right, sum-root->val);
23         return res;
24     }
25     int pathSum(TreeNode* root, int sum) {
26         if(root == nullptr)
27             return 0;
28         int res = 0;
29         res = pathSumCore(root, sum) + 
30             pathSum(root->left, sum) + pathSum(root->right, sum);
31         return res;
32     }
33 };
原文地址:https://www.cnblogs.com/LJ-LJ/p/11481641.html