leetcode 437. Path Sum III
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
解法1,DFS:
# 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 # java solution public class Solution { public int pathSum(TreeNode root, int sum) { if (root == null) return 0; return pathSumFrom(root, sum) + pathSum(root.left, sum) + pathSum(root.right, sum); } private int pathSumFrom(TreeNode node, int sum) { if (node == null) return 0; return (node.val == sum ? 1 : 0) + pathSumFrom(node.left, sum - node.val) + pathSumFrom(node.right, sum - node.val); } } """ def dfs(node, target): if not node: return 0 return int(node.val == target)+dfs(node.left, target-node.val)+dfs(node.right, target-node.val) if not root: return 0 return dfs(root, sum)+self.pathSum(root.left, sum)+self.pathSum(root.right, sum)
尤其注意是dfs(root, sum)+self.pathSum(root.left, sum)+self.pathSum(root.right, sum) 而不是dfs+dfs+dfs!容易出错!
另外解法就是前缀树的解法,前缀树记录sum,比如:
root = [10,5,-3,3,2,null,11,3,-2,null,1], sum = 8 10 / \ 5 -3 / \ \ 3 2 11 / \ \ 3 -2 1
到节点3的前缀sum就是{10:1, 15:1, 18:1},则包括节点3的满足sum=8的路径就是{10,5,3}这条通路减去{10}这条通路,两个前缀相减,更深的前缀-浅的前缀就是中间路路径,18-10=8满足条件。
代码:
# 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 traverse(node, total, pre_sum): if not node: return 0 total += node.val ans = pre_sum.get(total-sum, 0) pre_sum[total] = pre_sum.get(total, 0)+1 ans += traverse(node.left, total, pre_sum) + traverse(node.right, total, pre_sum) pre_sum[total] -= 1 return ans return traverse(root, 0, {0:1})