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]
]
来自 <https://leetcode.com/problems/path-sum-ii/>
题解:Path Sum题的变形,给出一个二叉树和一个值,求出所有路径上节点值得和与之相等的路径,并打印出所有路径。同样是路径遍历的问题,也可以考虑使用深度优先遍历的方法。我们看一下递归过程:
递归结束条件:当前节点为叶节点,也就是左右子树都为null时,终止递归,此时如果传递的sum值是0,就可以将当前递归过程的path加入到路径列表中,否则,就不需要加入。在终止递归前,需要将当前叶节点的值从path中移除,以便下一条路径的递归。
递归函数:分别对左右子树执行递归函数,完成后从path中删除当前节点。
public class PathSumII {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> paths = new ArrayList<>();
List<Integer> path = new ArrayList<>();
dfs(root, sum, paths, path);
return paths;
}
private void dfs(TreeNode root, int sum, List<List<Integer>> paths, List<Integer> path){
if(root == null)
return;
path.add(root.val);
if(root.left == null && root.right == null){
if(path.size() > 0 && sum-root.val == 0){
List<Integer> temp = new ArrayList<>();
path.forEach(x -> temp.add(x));
paths.add(temp);
}
path.remove(path.size()-1);
return;
}
// if(root == null && sum != 0){
// if(path.size() > 0){
// path.remove(path.size()-1);
// }
// return;
// }
dfs(root.left, sum-root.val, paths, path);
dfs(root.right, sum-root.val, paths, path);
path.remove(path.size()-1);
return;
}
}
本文详细解析了LeetCode上的Path Sum II题目,通过深度优先遍历算法寻找二叉树中所有根到叶子节点路径,使得路径上节点值之和等于给定的数值。示例展示了如何使用递归实现这一过程。
434

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



