LeetCode 113. Path Sum II
2020-05-20 21:16:44 # leetcode

Problem

LeetCode 113. Path Sum II

1. 题目简述

给出一棵二叉树和一个sum值,根节点为root,找出所有从根节点到叶子节点的和为sum的路径。例如:

Given the below binary tree and sum = 22,

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

Return:
[
[5,4,11,2],
[5,8,4,5]
]

2. 算法思路

DFS

此题难度为medium,思路和Path Sum 1差不多,也是DFS遍历所有路径,这里有两种做法,一种是保留根节点到当前节点的路径,遍历完成后从list中删除该节点,需要写一个辅助函数;另一种做法是返回左孩子和右孩子到根节点和为sum-root.val的路径,然后拼接。

第一次做的时候用的是解法2,存在较多的拼接操作,运行速度较慢,放在下面的解法2.

3. 解法

  1. 使用LinkedList保存当前路径,遍历后从currPath中删除当前节点,一定要删除!而且要注意,add到result里的时候,记得new一个对象,否则currPath会变。
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
/**
* 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 {

public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> currPath = new LinkedList();
pathSum(root, sum, currPath, result);
return result;
}

private void pathSum(TreeNode root, int sum, List<Integer> currPath, List<List<Integer>> result) {
if (root == null) {
return;
}

currPath.add(new TreeNode(root.val));
if (root.left == null && root.right == null && root.val == sum) {
result.add(new LinkedList(currPath));
} else {
pathSum(root.left, sum - root.val, currPath, result);
pathSum(root.right, sum - root.val, currPath, result);
}
currPath.remove(currPath.size() - 1);

}
}

  1. 不适用辅助函数,将左右节点返回的符合条件的list拼接起来
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
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result = new ArrayList<List<Integer>>();

if (root == null || (root.left == null && root.right == null && root.val != sum)) {
return result;
}

if (root.left == null && root.right == null && root.val == sum) {
List<Integer> path = new ArrayList();
path.add(root.val);
result.add(path);
return result;
}

List<List<Integer>> leftList = pathSum(root.left, sum - root.val);
List<List<Integer>> rightList = pathSum(root.right, sum - root.val);

if (leftList.size() == 0 && rightList.size() == 0) {
return result;
}

if (leftList.size() > 0) {
for (List<Integer> list : leftList) {
List<Integer> path = new ArrayList();
path.add(root.val);
path.addAll(list);
result.add(path);
}
}

if (rightList.size() > 0) {
for (List<Integer> list : rightList) {
List<Integer> path = new ArrayList();
path.add(root.val);
path.addAll(list);
result.add(path);
}
}

return result;

}
}