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)
            
    

      

  • 相关阅读:
    软件工程的实践项目的自我目标
    transform使用导致元素内字体出现模糊的坑~~~
    nvmw安装,用于控制node版本;
    开章大吉~
    eclipse运行Android项目出现“The connection to adb is down, and a severe error has occured. You must restart adb and Eclipse. ”
    Date对象相关函数使用
    Balsamiq Mockups 注册码
    如何关闭sublime更新提示
    如何在边框中加入文字
    如何用手机测试移动端页面
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6631789.html
Copyright © 2011-2022 走看看