Python3解leetcode 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

思路:

仍然是深度优先遍历的原则,该方法需要多做题多巩固啊!!占了我一整天时间的一道题。

从头到尾遍历每一个节点,记录从根节点到每一个节点的sum。

通过查找当前节点和目标sum之间的差值,进行相应剪枝动作

当退出当前层次时候,需要减去当前层次计算出来的和,故每次return之前都有一个减一的动作

代码:

 1 # Definition for a binary tree node.
 2 # class TreeNode:
 3 #     def __init__(self, x):
 4 #         self.val = x
 5 #         self.left = None
 6 #         self.right = None
 7 
 8 class Solution:
 9     def pathSum(self, root: TreeNode, sum: int) -> int:
10         if root == None : return 0
11         prefix = {0:1}
12         return self.Calc(root,0,sum,prefix)
13        
14         
15     def Calc(self,root,cursum,target,prefix):
16         if root == None : return 0
17         cursum += root.val
18         res = prefix.get(cursum - target,0)
19         prefix[cursum] = prefix.get(cursum,0) + 1
20         res += self.Calc(root.left,cursum,target,prefix)  + self.Calc(root.right,cursum,target,prefix)
21         prefix[cursum] = prefix.get(cursum) - 1
22         return res

 

posted on 2019-08-07 10:37  狂奔的蜗牛163  阅读(336)  评论(0编辑  收藏  举报