Description
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
Answer
总结来说两种方法:
- 暴力dfs搜索:对每个节点深度搜索一边来寻找符合题目的情景。
- 前缀和。
其实不难看出,暴力搜索是非常简单和直白的,但是时间复杂度就不太乐观了。
为了降低算法的时间复杂度,这里可以采用前缀和的思想。那么什么是前缀和呢?
前缀和在这里可以理解为从根节点到该节点的和,即根节点到当前节点路径上所有元素的和。那么这道问题就变成,是否在当前节点找到前缀和为当前节点的前缀和减去sum的节点,如果有的话,count就加一。以此类推。
前缀和可以以**O(n)**的时间复杂度返回结果。下次面试官问你O(n)解法的时候不要再愣住啦。
Code
暴力搜索
/**
* 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 count = 0;
void dfs(TreeNode* root, int sum) {
if (!root)
return;
if (sum == root -> val)
count++;
dfs(root -> left, sum - root -> val);
dfs(root -> right, sum - root -> val);
}
int pathSum(TreeNode* root, int sum) {
if (!root)
return count;
dfs(root, sum);
pathSum(root -> left, sum);
pathSum(root -> right, sum);
return count;
}
};
前缀和
/**
* 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:
unordered_map<int, int> count;
int helper(TreeNode* root, int pre_sum, int sum) {
if (!root)
return 0;
int res = 0;
pre_sum += root -> val;
res += count[pre_sum - sum];
count[pre_sum]++;
res += helper(root -> left, pre_sum, sum) + helper(root -> right, pre_sum, sum);
count[pre_sum]--;
return res;
}
int pathSum(TreeNode* root, int sum) {
count[0] = 1;
return helper(root, 0, sum);
}
};