leetcode 437. Path Sum III
阿新 • • 發佈:2018-05-25
con null nodes strong tar 滿足 AR 出錯 IT
,18-10=8滿足條件。
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}這條通路,兩個前綴相減,更深的前綴-淺的前綴就是中間路路徑
代碼:
# 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})
leetcode 437. Path Sum III