LeetCode 113. Path Sum II

原题链接在这里: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]
]

题解:

DFS state needs current node, current sum and target sum, current item and res.

DFS returns void.

DFS stop condition when current node is null. Or when current node is leaf.

If current node node is not null, add current node value and check if it is leaf.

Note:1. 当res加item时一定要res.add(new ArrayList(item)), 因为list 是 pass by reference, 后面若更改item, 则已经加到res里的item也会同时更改.

2. Because of 2 return condition, before leaf return, also need to backtrack.

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 class Solution {
11     public List<List<Integer>> pathSum(TreeNode root, int sum) {
12         List<List<Integer>> res = new ArrayList<>();
13         if(root == null){
14             return res;
15         }
16         
17         dfs(root, 0, sum, new ArrayList<Integer>(), res);
18         return res;
19     }
20     
21     private void dfs(TreeNode root, int cur, int sum, List<Integer> item, List<List<Integer>> res){
22         if(root == null){
23             return;
24         }
25         
26         item.add(root.val);
27         cur += root.val;
28         if(root.left == null && root.right == null){
29             if(cur == sum){
30                 res.add(new ArrayList<Integer>(item));
31             }
32             
33             item.remove(item.size() - 1);
34             return;
35         }
36         dfs(root.left, cur, sum, item, res);
37         dfs(root.right, cur, sum, item, res);
38         item.remove(item.size() - 1);
39     }
40 }

类似Path Sum