leetcode解题 : Path Sum III (437)

You are given a binary tree in which each node contains an integer value.

Find the number of paths that sum to a given value.

The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).

The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.

Example:

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

  10
 /  \
5   -3

/ \ \
3 2 11
/ \ \
3 -2 1

Return 3. The paths that sum to 8 are:

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

解法1:DFS / Recursion

这题考察DFS的基本知识。因为考虑的是每一个从上到下的path,那么应该要想到要用DFS。
对于每一个节点,如果包括自己,则可以递归运算left 和right,而要match的数则变成了sum - val。
如果不包括自己,则直接运算left和right,最后将两个情况相加就是结果。
实际上这里就是用了一个preorder遍历,回想一下preorder的算法:
visit root;
visit left;
visit right;
这里也一样:
visit root => compute number of paths with root (dfs(root, sum))
visit left => compute number of paths with left (pathSum(root->left, sum))
visit right => compute number of paths with right (pathSum(root->right, sum))

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
/**
* 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 left = pathSum(root->left, sum);
int right = pathSum(root->right, sum);
return dfs(root, sum) + left + right;
}
int dfs(TreeNode* root, int sum) {
int res = 0;
if (root == NULL) {
return res;
}
if (root->val == sum) {
res++;
}
res += dfs(root->left, sum - root->val);
res += dfs(root->right, sum - root->val);
return res;
}
};

Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int pathSum(TreeNode root, int sum) {
if (root == null) {
return 0;
}
int left = pathSum(root.left, sum);
int right = pathSum(root.right, sum);
// Count the number of paths starting from the current root
int startingFromThisRoot = dfs(root, sum);
return startingFromThisRoot + left + right;
}
private int dfs(TreeNode root, int sum) {
int res = 0;
if (root == null) return res;
if (root.val == sum) ++res;
res += dfs(root.left, sum - root.val);
res += dfs(root.right, sum - root.val);
return res;
}
}