/** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ 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); } }
https://leetcode.com/problems/path-sum-iii/#/description
补充一个python实现,使用递归:
1 class Solution: 2 def pathSum(self, root: 'TreeNode', sum: 'int') -> 'int': 3 if root == None: 4 return 0 5 return self.pathSumWithRoot(root,sum) + self.pathSum(root.left,sum) + self.pathSum(root.right,sum) 6 7 def pathSumWithRoot(self,root,sum): 8 if root == None: 9 return 0 10 ret = 0 11 if root.val == sum: 12 ret += 1 13 ret += self.pathSumWithRoot(root.left,sum-root.val) + self.pathSumWithRoot(root.right,sum-root.val) 14 return ret
这种实现的时间复杂度是O(n^2),执行效率比较低。
再补充一个更高效的实现,使用hash表进行缓存:(如果必须符合这个时间复杂度的要求O(n),就可以当作hard级别的题目了)
1 class Solution(object): 2 def pathSum(self, root, target): 3 # define global result and path 4 self.result = 0 5 cache = {0:1} 6 7 # recursive to get result 8 self.dfs(root, target, 0, cache) 9 10 # return result 11 return self.result 12 13 def dfs(self, root, target, currPathSum, cache): 14 # exit condition 15 if root is None: 16 return 17 # calculate currPathSum and required oldPathSum 18 currPathSum += root.val 19 oldPathSum = currPathSum - target 20 # update result and cache 21 self.result += cache.get(oldPathSum, 0) 22 cache[currPathSum] = cache.get(currPathSum, 0) + 1 23 24 # dfs breakdown 25 self.dfs(root.left, target, currPathSum, cache) 26 self.dfs(root.right, target, currPathSum, cache) 27 # when move to a different branch, the currPathSum is no longer available, hence remove one. 28 cache[currPathSum] -= 1