zoukankan      html  css  js  c++  java
  • LeetCode 124. Binary Tree Maximum Path Sum

    原题

    Given a binary tree, find the maximum path sum.

    For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.

    For example:
    Given the below binary tree,

           1
          / 
         2   3
    

    Return 6.

    解题思路

    1. 递归求解
    2. 简化问题,先考虑全是正数的情况下的解法
    3. 重点:需要两个最大值,一个是当前树的最大路径,即当前节点值加上左右子树的节点值;另一个是当前树向父节点提供的最大路径,这个值应该是根节点的值加上路径最长的子树那边的最大路径,向上层递归函数返回这个值。
    4. 于是考虑到负值的话即为:需要两个最大值,一个是当前树的最大路径,即当前节点值加上左右子树的路径和(如果左右子树路径和为正的话);另一个是当前树向父节点提供的最大路径,这个值应该是根节点的值加上路径最长的子树那边的最大路径,向上层递归函数返回这个值。

    完整代码

    # 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
            """
            if root == None:
                return 0
            self.maxSum = -sys.maxint
            self._maxPathSum(root)
            return self.maxSum
            
        def _maxPathSum(self, node):
            """
            :type node: TreeNode
            :rtype: 对于上层根的最大路径和
            """
            if node == None:
                return 0
            node_max = node.val
            lPathSum, rPathSum = self._maxPathSum(node.left), self._maxPathSum(node.right)
            if lPathSum > 0:
                node_max += lPathSum
            if rPathSum > 0:
                node_max += rPathSum
            # 求此节点当为根节点时的最大路径和
            if self.maxSum < node_max:
                self.maxSum = node_max
            # 返回对于上层根节点的最大路径和    
            return max(node.val, node.val + lPathSum, node.val + rPathSum)
            
    

      

  • 相关阅读:
    Jenkins简明入门(三) -- Blue Ocean,让一切变得简单
    TeamForge使用指南
    Jenkins简明入门(二) -- 利用Jenkins完成Python程序的build、test、deployment
    谈谈Python中的decorator装饰器,如何更优雅的重用代码
    Jenkins简明入门(一) -- 安装
    Python CSV 超简明用法
    Intel CPU命名规则的简略解析
    ef core 2.1 利用Query Type查询视图
    asp.net core 开发环境自定义域名及端口
    ef core 使用include进行外键连接查询
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6631789.html
Copyright © 2011-2022 走看看