You are given a binary tree in which each node contains an integer value.
Find the number of paths that sum to a given value.
The path does not need to start or end at the root or a leaf, but it must go downwards (traveling only from parent nodes to child nodes).
The tree has no more than 1,000 nodes and the values are in the range -1,000,000 to 1,000,000.
Example:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1 Return 3. The paths that sum to 8 are: 1. 5 -> 3 2. 5 -> 2 -> 1 3. -3 -> 11<Solution>
想法如下(參考資料)
- 用一個 hash map 記錄從 root 到前一個 node 的總合,以及出現的次數
- 如果 curSum - target 在 hash map 裡面有資料,代表在前面一定有總合為 target 的 path 存在
- 利用 DFS 的方式來歷遍
C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
int pathSum(TreeNode* root, int sum) { | |
if(!root) { | |
return 0; | |
} | |
unordered_map<int, int> preSumMap; | |
preSumMap[0] = 1; | |
return dfs(root, 0, sum, preSumMap); | |
} | |
int dfs(TreeNode *node, int curSum, const int &target, unordered_map<int, int> &map) { | |
if(!node) { | |
return 0; | |
} | |
curSum += node->val; | |
const int key = curSum - target; | |
int cnt = map.count(key) ? map[key] : 0; | |
map[curSum]++; | |
cnt += dfs(node->left, curSum, target, map) + dfs(node->right, curSum, target, map); | |
map[curSum]--; | |
return cnt; | |
} | |
}; |
另一種解法純粹是 recursive,不用 hashmap
想法如下
- 第一層 recursive,選 root,或者選 root.left,或者選 root.right
- 第二層 recursive,純粹歷遍,找有沒有答案
Java(參考解法)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Definition for a binary tree node. | |
* public class TreeNode { | |
* int val; | |
* TreeNode left; | |
* TreeNode right; | |
* TreeNode(int x) { val = x; } | |
* } | |
*/ | |
class Solution { | |
public int pathSum(TreeNode root, int sum) { | |
if(root == null) { | |
return 0; | |
} | |
return dfs(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); | |
} | |
private int dfs(TreeNode root, int sum) { | |
if(root == null) { | |
return 0; | |
} | |
return (root.val == sum ? 1 : 0) + dfs(root.left, sum - root.val) + dfs(root.right, sum - root.val); | |
} | |
} |
沒有留言:
張貼留言