加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

Python3解leetcode Path Sum III

发布时间:2020-12-20 12:45:28 所属栏目:Python 来源:网络整理
导读:问题描述: 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

问题描述:

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.

Example:

root = [10,5,-3,3,2,null,11,-2,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,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,prefix)  + self.Calc(root.right,prefix)
21         prefix[cursum] = prefix.get(cursum) - 1
22         return res

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读