Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For 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] ]
题目含义:找到所有从根节点到叶子节点的路径,使得路径上节点总和等于给定值num
1 private List<List<Integer>> paths = new ArrayList<>(); 2 private void find(TreeNode root, List<Integer> values, int currentSum, int targetSum) { 3 if (root == null) return; 4 values.add(root.val); 5 currentSum += root.val; 6 7 if (root.left != null && root.right != null) { 8 find(root.left, values, currentSum, targetSum); 9 find(root.right, values, currentSum, targetSum); 10 } else if (root.left != null) find(root.left, values, currentSum, targetSum); 11 else if (root.right != null) find(root.right, values, currentSum, targetSum); 12 else if (currentSum == targetSum) //只能是叶子节点,才开始比较值 13 { 14 List<Integer> path = new ArrayList<>(values.size()); 15 path.addAll(values); 16 paths.add(path); 17 } 18 values.remove(values.size() - 1);//找到了叶子节点,但是总和不等于目标值,将该叶子节点从values中删除,保证还能使用其上面的values集合来累加其它叶子节点 19 } 20 21 public List<List<Integer>> pathSum(TreeNode root, int sum) { 22 find(root, new ArrayList<>(), 0, sum); 23 return paths; 24 }