题目链接 113.路径总和II
前序遍历
path更新过程:
[5,]
[5,4]
[5,4,11]
[5,4,11,7]
因为7是叶子节点,travesal(root.left, count);travesal(root.right, count);均在遇到if (root == null) return;后就返回了,所以回溯
[5,4,11]
[5,4,11,2]添加到result中
回溯
[5,4,11]
回溯
[5,4]
回溯
[5]
[5,8]
[5,8,3]
回溯
[5,8,4]
[5,8,4,5]添加到result中
回溯
[5,8,4]
[5,8,4,1]
遍历结束
// 解法2
class Solution {
List<List<Integer>> result;
LinkedList<Integer> path;
public List<List<Integer>> pathSum (TreeNode root,int targetSum) {
result = new LinkedList<>();
path = new LinkedList<>();
travesal(root, targetSum);
return result;
}
private void travesal(TreeNode root, int count) {
if (root == null) return;
path.offer(root.val);
count -= root.val;
if (root.left == null && root.right == null && count == 0) {
result.add(new LinkedList<>(path));
}
travesal(root.left, count);
travesal(root.right, count);
path.removeLast(); // 回溯
}
}
需要注意,这里的path 和 result都是LinkedList来存储,以便path使用removeLast方法删除最后一个元素。