zoukankan      html  css  js  c++  java
  • 边工作边刷题:70天一遍leetcode: day 14-1

    Binary Tree Maximum Path Sum

    错误点:negative也可能是最大值,所以global maxVal初始值为INT_MIN。但是左右传上来的一侧值(left or right)一定要先和0比较再加到local maxVal做比较,因为如果left or right是negative,那么root可以选择不用。

    # 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 maxPathSum(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.maxSum = -sys.maxint-1
            if not root: return 0
            self.maxdfs(root)
            return self.maxSum
            
        def maxdfs(self, root):
            leftMax = 0 
            if root.left:
                leftMax = max(0, self.maxdfs(root.left))
                
            rightMax = 0
            if root.right:
                rightMax = max(0, self.maxdfs(root.right))
            
            if leftMax + rightMax + root.val>self.maxSum:
                self.maxSum = leftMax + rightMax + root.val
            
            return max(leftMax+root.val, rightMax+root.val, root.val)
    
  • 相关阅读:
    ble_app_hrs心率程序 nrf51822
    2019.05.08 《Linux驱动开发入门与实战》
    函数指针
    typedef
    回调函数
    android2
    android1
    每周总结2
    HTML
    数组(续)
  • 原文地址:https://www.cnblogs.com/absolute/p/5677832.html
Copyright © 2011-2022 走看看