zoukankan      html  css  js  c++  java
  • 【leetcode】124. Binary Tree Maximum Path Sum

    题目如下:

    Given a non-empty 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.

    Example 1:

    Input: [1,2,3]
    
           1
          / 
         2   3
    
    Output: 6
    

    Example 2:

    Input: [-10,9,20,null,null,15,7]
    
       -10
       / 
      9  20
        /  
       15   7
    
    Output: 42

    解题思路:题目所要求的最大路径约束条件的是最多只有一个节点的左右节点同时存在于路径中,当然这个节点可以不是根节点。假设其中一个节点a是这样的节点,那么a可以组成的最大路径和就是 max(a.val,a.val+left_child_max_val,a.val+right_child_max_val,a.val+left_child_max_val+right_child_max_val),这里的意思是a本身是最大值、a与左子树组成最大值、a与右子树组成最大值、a与左右子树同时组成最大值。这时a的左右子树的最大值分别是多少呢,以a的左子树为例,根据题目的约束,a已经是唯一一个左右节点同时存在于路径中的节点,那么a的左子树的最大值就只有max(a.left.val,a.left.+left_child_max_val,a.left.+right_child_max_val)三种情况了,即只能自身、和左子树、和右子树组成最大值。遍历整个二叉树,计算出每个节点作为这样一个特殊节点可以组成的最大路径的最大值即可。因为有很多重复的计算,因此可以缓存每个节点的左右子树的最大值以提高效率。

    代码如下:

    # 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):
        res = -float('inf')
        dic_left = {}
        dic_right = {}
        def getMax(self,node):
            if node == None:
                return 0
            if node in self.dic_left:
                lv = self.dic_left[node]
            else:
                lv = self.getMax(node.left)
                self.dic_left[node] = lv
            if node in self.dic_right:
                rv = self.dic_right[node]
            else:
                rv = self.getMax(node.right)
                self.dic_right[node] = rv
            return max(node.val,node.val+lv,node.val+rv)
        def recursive(self,node):
            if node == None:
                return
            lv = self.getMax(node.left)
            rv = self.getMax(node.right)
            self.res = max(self.res, node.val, node.val + lv ,node.val + rv,node.val + lv + rv)
            self.recursive(node.left)
            self.recursive(node.right)
    
        def maxPathSum(self, root):
            """
            :type root: TreeNode
            :rtype: int
            """
            self.dic_left = {}
            self.dic_right = {}
            self.recursive(root)
            return self.res
  • 相关阅读:
    【原创】贴片电容的测量方法。。。这是我从自己QQ空间转过来的,本人实操!
    CentOS6.4安装Apache+MySQL+PHP
    第一次在博客园写博客。。。新人
    C# 简单生成双色球代码
    从客户端中检测到有潜在危险的 Request.Form 值 方法
    经典实例
    js鼠标键禁用功能
    逻辑思维题
    C#运算符笔记
    C#基础
  • 原文地址:https://www.cnblogs.com/seyjs/p/10555758.html
Copyright © 2011-2022 走看看