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
            
            
            
            
            
            
            
            
            
            
            
            
            
            
    

      

  • 相关阅读:
    最小化x11 debian
    chroot后 运行xeyes Error: Can't open display: :0.0
    std::bind1st和std::bind2nd
    bind1nd,not1,compose1等用法
    python中*和**的参数
    QT静态编译
    Qt中QEvent和信号槽的区别
    JSON文件内容加注释的几种方法
    C语言--#、##、__VA_ARGS__ 和##__VA_ARGS__ 的使用
    QT正则表达式
  • 原文地址:https://www.cnblogs.com/LiCheng-/p/6892562.html
Copyright © 2011-2022 走看看