• 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
  • 相关阅读:
    Java基础知识总结(绝对经典)
    mybatis注解详解
    div行内样式style常用属性
    php中json_decode()和json_encode()的使用方法
    java调用javascript :js引擎rhino
    DeleteDC() 与 ReleaseDC() 的区别 [转]
    non-manifold Mesh(非流形网格)
    C++静态成员函数小结 [转]
    C++ 类的静态成员详细讲解[转]
    CString 转 char*; wstring 转 string
  • 原文地址:https://www.cnblogs.com/xiaohua92/p/11313781.html
Copyright © 2020-2023  润新知