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
            """
            self.maxPath = -sys.maxint
            self.helper(root)
            return self.maxPath
            
        def helper(self, node):
            if node == None:
                return 0
            lMax = self.helper(node.left)
            rMax = self.helper(node.right)
            # 局部最大路径 = 根节点值 + 左、右最大路径(必须为正才能加)
            MaxSum = node.val
            if lMax > 0:
                MaxSum += lMax
            if rMax > 0:
                MaxSum += rMax
            self.maxPath = max(self.maxPath, MaxSum)
            # 返回值为单一路径最大值,如果左、右最大路径均为负,则返回根节点值
            return max(lMax, rMax, 0) + node.val
            
            
            
            
            
            
            
            
            
            
            
            
            
            
    

      

  • 相关阅读:
    netstat
    Android总结篇——Intent机制详解及示例总结
    Android系统介绍与框架
    三个绘图工具类详解
    Android 调用 WebService
    Android JSON数据解析
    Android 总结:ContentProvider 的使用
    Android Service完全解析,关于服务你所需知道的一切(下)
    Android Service完全解析,关于服务你所需知道的一切(上)
    Activity的四种加载模式详解:
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6892562.html
Copyright © 2011-2022 走看看