题目:
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
解释:
返回二叉树中路径和为sum的路径的个数,需要注意的是路径无需从root开始以leaf结束,也是经典的dfs问题。其实也不需要把path记录下来,因为是求路径和,所以只需要把路径和传入即可。
递归的写法,内层函数调用需要递归,外层函数调用还需要递归,会重复计算,速度特别慢,是暴力的无记忆递归解法:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
def dfs(root,sum):
res=0
if root==None:
return res
if root.val==sum:
res+=1
if root.left:
res+=dfs(root.left,sum-root.val)
if root.right:
res+=dfs(root.right,sum-root.val)
return res
if root==None:
return 0
left,right=0,0
if root.left:
left=self.pathSum(root.left,sum)
if root.right:
right=self.pathSum(root.right,sum)
return dfs(root,sum)+left+right
记忆化,用一个字典记录,真是牛逼了…
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import defaultdict
class Solution:
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: int
"""
self.result=0
curSum=defaultdict(int)
curSum[0]=1
def helper(curSum,root,curVal,target):
if not root:
return
#curValue表示从root到当前结点的路径的和
curVal+=root.val
self.result+=curSum[curVal-target]
curSum[curVal]+=1
if root.left:
helper(curSum,root.left,curVal,target)
if root.right:
helper(curSum,root.right,curVal,target)
curSum[curVal]-=1
if root:
helper(curSum,root,0,sum)
return self.result
c++代码:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
#include <map>
using namespace std;
class Solution {
int result;
public:
int pathSum(TreeNode* root, int sum) {
map<int,int>curSum;
curSum[0]=1;
if (root)
helper(root,curSum,0,sum);
return result;
}
void helper(TreeNode*root ,map<int,int>& curSum,int curVal,int target)
{
if (!root)
return ;
curVal+=root->val;
result+=curSum[curVal-target];
curSum[curVal]++;
if (root->left)
helper(root->left,curSum,curVal,target);
if(root->right)
helper(root->right,curSum,curVal,target);
curSum[curVal]--;
}
};
总结:
在dfs的时候使用记忆化可以避免重复计算加快速度,多重dfs简直是人间灾难。