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);}}
