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 }

AC C++:

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 8  *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 9  *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
10  * };
11  */
12 class Solution {
13 public:
14     vector<vector<int>> pathSum(TreeNode* root, int targetSum) {
15         vector<vector<int>> res;
16         vector<int> item;
17         dfs(root, targetSum, item, res);
18         return res;
19     }
20 
21 private:
22     void dfs(TreeNode* root, int targetSum, vector<int>& item, vector<vector<int>>& res){
23         if(!root){
24             return;
25         }
26 
27         item.push_back(root->val);
28         targetSum -= root->val;
29         if(!root->left && !root->right && targetSum == 0){
30             res.push_back(item);
31         }
32 
33         dfs(root->left, targetSum, item, res);
34         dfs(root->right, targetSum, item, res);
35         item.pop_back();
36     }
37 };

AC Python:

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, val=0, left=None, right=None):
 4 #         self.val = val
 5 #         self.left = left
 6 #         self.right = right
 7 class Solution:
 8     def pathSum(self, root: Optional[TreeNode], targetSum: int) -> List[List[int]]:
 9         res = []
10         self.dfs(root, targetSum, [], res)
11         return res
12     
13     def dfs(self, root: Optional[TreeNode], targetSum: int, item: [], res: [[]]):
14         if not root:
15             return
16         
17         item.append(root.val)
18         targetSum -= root.val
19         if not root.left and not root.right and targetSum == 0:
20             res.append(item.copy())
21         
22         self.dfs(root.left, targetSum, item, res)
23         self.dfs(root.right, targetSum, item, res)
24         item.pop()
25         

类似Path Sum

posted @ 2015-09-07 04:14  Dylan_Java_NYC  阅读(561)  评论(0编辑  收藏  举报