Path Sum总结

Path Sum类型题的思路就是进行DFS。编写DFS函数的时候要想明白:1.DFS函数的作用是干什么 2.DFS函数的base case是什么 3.DFS函数的输入输出分别是什么

  1. Path Sum
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
38
39
40
41
42
43
44
45
46
/*
112. Path Sum
Easy

1198

380

Favorite

Share
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public boolean hasPathSum(TreeNode root, int sum) {
if(root==null)
return false;
if(root.left==null && root.right==null && root.val==sum)
return true;
return hasPathSum(root.left, sum-root.val) || hasPathSum(root.right, sum-root.val);
}
}
  1. Path Sum II: 这道题的关键是判断好recursive的base case,不像其他很多的DFS的base case直接就是node==null,这里的base case应该有两个:1. node==null,直接返回 2. node不为空,且node.left==null&&node.right==null&&node.val==sum,这个时候我们把存下来的路线加入到结果中。
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
113. Path Sum II
Medium

1131

42

Favorite

Share
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

Note: A leaf is a node with no children.

Example:

Given the below binary tree and sum = 22,

5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
Return:

[
[5,4,11,2],
[5,8,4,5]
]
*/

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ans = new LinkedList<>();
dfs(root, ans, sum, new LinkedList<>());
return ans;
}

private void dfs(TreeNode node, List<List<Integer>> ans, int sum, List<Integer> l){
if(node==null){
return;
}

if(node.left==null && node.right==null && node.val==sum){
l.add(node.val);
ans.add(new LinkedList<>(l));
l.remove(l.size()-1);
return;
}

l.add(node.val);
dfs(node.left, ans, sum-node.val, l);
dfs(node.right, ans, sum-node.val, l);
l.remove(l.size()-1);
}
}
  1. Path Sum III: 这道题可以直接DFS做,但是要考虑到可能的path不止可以是从root开始,而是可以从任意一个node开始,所以如果直接DFS的话要用两个DFS函数,而且相当于brute force。
    比较好的方法是使用类似two sum的presum做法,使用一个map存储遇到过的presum的frequency。
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/*
437. Path Sum III
Easy

2320

144

Favorite

Share
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
*/
/**
* 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) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 1);
return helper(root, 0, sum, map);
}

private int helper(TreeNode node, int curSum, int sum, Map<Integer, Integer> map){
if(node==null){
return 0;
}

curSum = curSum + node.val;

int res = map.getOrDefault(curSum-sum, 0);
map.put(curSum, map.getOrDefault(curSum, 0)+1);
res = res + helper(node.left, curSum, sum, map)+helper(node.right, curSum, sum, map);
map.put(curSum, map.get(curSum)-1);
return res;
}
}

下面两道题的思路很类似,都是求maximum path sum,思路就是正常进行DFS,DFS求的是从input node到叶节点的max path sum,而不是直接求整棵树的max path sum,在过程中,我们使用一个max变量来计算目前遇到过的最大的pathsum。

  1. Binary Tree Maximum Path Sum:
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/*
124. Binary Tree Maximum Path Sum
Hard

2158

169

Favorite

Share
Given a non-empty binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

1
/ \
2 3

Output: 6
Example 2:

Input: [-10,9,20,null,null,15,7]

-10
/ \
9 20
/ \
15 7

Output: 42
*/

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int maxPathSum(TreeNode root) {
int[] ans = new int[]{Integer.MIN_VALUE};
longestPath(ans, root);
return ans[0];
}

private int longestPath(int[] ans, TreeNode node){
if(node==null){
return 0;
}
int left = Math.max(0, longestPath(ans, node.left));
int right = Math.max(0, longestPath(ans, node.right));
ans[0] = Math.max(ans[0], left+right+node.val);
return Math.max(left, right) + node.val;
}
}
  1. Diameter of Binary Tree
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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/*
543. Diameter of Binary Tree
Easy

1780

111

Favorite

Share
Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.

Example:
Given a binary tree
1
/ \
2 3
/ \
4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].

Note: The length of path between two nodes is represented by the number of edges between them.
*/

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int diameterOfBinaryTree(TreeNode root) {
int[] ans = new int[]{0};
longestPath(ans, root);
return ans[0];
}

private int longestPath(int[] ans, TreeNode node){
if(node==null){
return 0;
}

int left = longestPath(ans, node.left);
int right = longestPath(ans, node.right);
ans[0] = Math.max(ans[0], left+right+1-1);
return Math.max(left, right)+1;
}
}