原题链接在这里:https://leetcode.com/problems/path-sum-ii/
题目:
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] ]
题解:
与Path Sum相似.
DFS, 终止条件是当遇到叶子节点时判断sum是否为0, 若是则res加当前item. 若root.left 不为空,左节点继续dfs, 用完后要remove掉尾节点, 右侧相同.
Note:1. 当res加item时一定要res.add(new ArrayList(item)), 因为list 是 pass by reference, 后面若更改item, 则已经加到res里的item也会同时更改。
2. 去掉list尾部就用list.remove(list.size()-1).
Time Complexity: O(n), 每个叶子节点都需要检查.
Space: O(nlogn), 一个item长度是logn, 最多可以有n/2组item, res大小是nlogn, n 是树总共的节点数. 用了logn层stack.
AC Java:
1 /** 2 * Definition for a binary tree node. 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 public class Solution { 11 public List<List<Integer>> pathSum(TreeNode root, int sum) { 12 List<List<Integer>> res = new ArrayList<List<Integer>>(); 13 if(root == null){ 14 return res; 15 } 16 17 dfs(root, sum, new ArrayList<Integer>(), res); 18 return res; 19 } 20 21 private void dfs(TreeNode root, int sum, List<Integer> item, List<List<Integer>> res){ 22 sum -= root.val; 23 item.add(root.val); 24 25 if(root.left == null && root.right == null && sum == 0){ 26 res.add(new ArrayList<Integer>(item)); 27 return; 28 } 29 if(root.left != null){ 30 dfs(root.left, sum, item, res); 31 item.remove(item.size()-1); 32 } 33 if(root.right != null){ 34 dfs(root.right, sum, item, res); 35 item.remove(item.size()-1); 36 } 37 } 38 }