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)
            
    

      

  • 相关阅读:
    利用定时器实时显示<input type="range"/>的值
    javascript日常总结
    SpringCloud如何上传大文件
    SpringBoot如何上传大文件
    SpringMVC如何上传大文件
    CSharp如何上传大文件
    C#如何上传大文件
    C#.NET如何上传大文件
    .NET如何上传大文件
    word文档的图片怎么保存到动易CMS上
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6631789.html
Copyright © 2011-2022 走看看