Path Sum II (M)
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]
]
题意
判断给定树中是否存在这样一条从根到叶的路径,使得路径上的数字之和等于目标值。记录下所有这样的路径。
思路
在 112. Path Sum 的基础上,保存所有符合条件的路径。依然是回溯法。
代码实现
/**
* 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 ArrayList<>();
pathSum(root, 0, sum, new ArrayList<>(), ans);
return ans;
}
private void pathSum(TreeNode x, int preSum, int sum, List<Integer> list, List<List<Integer>> ans) {
if (x == null) {
return;
}
list.add(x.val);
if (preSum + x.val == sum && x.left == null && x.right == null) {
ans.add(new ArrayList<>(list));
} else {
pathSum(x.left, preSum + x.val, sum, list, ans);
pathSum(x.right, preSum + x.val, sum, list, ans);
}
list.remove(list.size() - 1);
}
}
本文深入探讨了PathSumII算法,旨在寻找二叉树中所有从根节点到叶子节点的路径,这些路径上的节点值之和等于给定的目标值。通过回溯法,我们能够有效地找到并记录下所有符合条件的路径。
642

被折叠的 条评论
为什么被折叠?



