题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
返回:
提示:
节点总数 <= 10000
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof
解题思路
基本思想就是使用回溯法+dfs(深度优先遍历)
值得注意的点:
- 每一条路径的开始节点是根节点,结束节点是叶子节点
- 添加list的时候,记得重新new一个list,不要直接传入list,否则传入的是引用
代码
/**
* 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>> list = new ArrayList<>();
// 回溯
backTrack(root, sum, new ArrayList<>(), list);
return list;
}
private void backTrack(TreeNode root, int sum, List<Integer> tempList, List<List<Integer>> list) {
// 校验
if (root == null) {
return;
}
// 重新计算sum和添加元素
sum -= root.val;
tempList.add(root.val);
// 满足条件且为叶子节点
if (sum == 0 && root.left == null && root.right == null) {
// 这个地方一定要注意,需要重新new一个ArrayList添加,否则添加的是引用
list.add(new ArrayList<>(tempList));
} else {
// 递归查找左子树和右子树
backTrack(root.left, sum, tempList, list);
backTrack(root.right, sum, tempList, list);
}
// 撤销
tempList.remove(tempList.size() - 1);
}
}