LC.P437[路径总和III]

方法一:DFS

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() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int ans, target;

public int pathSum(TreeNode root, int targetSum) {
this.target = targetSum;
dfs1(root);
return ans;
}

private void dfs1(TreeNode node) {
if (node == null) return;
dfs2(node, node.val);
dfs1(node.left);
dfs1(node.right);
}

private void dfs2(TreeNode node, long val) {
if (val == target) ++ans;
if (node.left != null) dfs2(node.left, node.left.val + val);
if (node.right != null) dfs2(node.right, node.right.val + val);
}
}
  • 时间复杂度:$O(n^2)$
  • 空间复杂度:$O(n)$

方法二:前缀和+DFS+回溯

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.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int ans, target;
Map<Long, Integer> map;

public int pathSum(TreeNode root, int targetSum) {
if (root == null) return 0;
this.target = targetSum;
map = new HashMap<>();
map.put(0L, 1);
dfs(root, root.val);
return ans;
}

private void dfs(TreeNode node, long val) {
if (map.containsKey(val - target)) ans += map.get(val - target);
map.merge(val, 1, Integer::sum);
if (node.left != null) dfs(node.left, node.left.val + val);
if (node.right != null) dfs(node.right, node.right.val + val);
map.put(val, map.getOrDefault(val, 0) - 1);
}
}
  • 时间复杂度:$O(n)$
  • 空间复杂度:$O(n)$