LeetCode: Path Sum II 解题报告

时间:2023-06-07 11:33:44

Path Sum II

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

For 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]
]

SOLUTION 1:

使用递归解决,先把下一个可能要加的节点加入到path中,再使用递归依次计算即可。

 /**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> path = new ArrayList<Integer>();
if (root == null) {
return ret;
} path.add(root.val);
sum -= root.val; dfs(root, sum, path, ret); return ret;
} public void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> ret) {
if (root == null) {
return;
} if (sum == 0 && root.left == null && root.right == null) {
ret.add(new ArrayList<Integer>(path));
return;
} if (root.left != null) {
path.add(root.left.val);
dfs(root.left, sum - root.left.val, path, ret);
path.remove(path.size() - 1);
} if (root.right != null) {
path.add(root.right.val);
dfs(root.right, sum - root.right.val, path, ret);
path.remove(path.size() - 1);
}
}
}

SOLUTION 2:

使用递归解决,如果只考虑加入当前节点,会更加简单易理解。递归的base case就是:

1. 当null的时候返回。

2. 当前节点是叶子 并且sum与root的值相同,则增加一个可能的解。

3. 如果没有解,将sum 减掉当前root的值,并且向左树,右树递归即可。

 // SOLUTION 2
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<List<Integer>>(); List<Integer> path = new ArrayList<Integer>();
if (root == null) {
return ret;
} dfs2(root, sum, path, ret); return ret;
} public void dfs2(TreeNode root, int sum, List<Integer> path, List<List<Integer>> ret) {
if (root == null) {
return;
} path.add(root.val);
sum -= root.val;
if (sum == 0 && root.left == null && root.right == null) {
ret.add(new ArrayList<Integer>(path));
} else {
dfs2(root.left, sum, path, ret);
dfs2(root.right, sum, path, ret);
} path.remove(path.size() - 1);
}