题目:
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.
解答:
本题为 LeetCode 112 题的进阶版。通过 DFS 深度优先搜索,找到满足的路径。在这种寻找不唯一路径的题目中,用到了之前多次用过的递归回溯的方法
具体思路如下:
- 从根节点开始,依次搜索其左右节点,每次递归时都将 sum 值减去当前节点的值
- 若遍历到叶子节点后依然没有形成合法路径,即当 root==null 时,则直接 return
- 若节点为叶子节点,即
root.left == null && root.right == null
,且当前路径的值和为 sum,则形成合法路径并保存进 res - 否则,则回到离当前节点最近的根节点,删除 list 中最后一个节点数,并继续遍历
代码实现如下:
class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
findPath(root, sum, res, list);
return res;
}
private void findPath(TreeNode root, int sum, List<List<Integer>> res, List<Integer> list){
if(root == null) {
return;
}
list.add(root.val);
if(root.left == null && root.right == null && root.val == sum) {
res.add(new ArrayList<>(list));
} else {
findPath(root.left, sum-root.val, res, list);
findPath(root.right, sum-root.val, res, list);
}
list.remove(list.size()-1);
}
}