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
  • 相关阅读:
    HDU Railroad (记忆化)
    HDU 1227 Fast Food
    HDU 3008 Warcraft
    asp vbscript 检测客户端浏览器和操作系统(也可以易于升级到ASP.NET)
    Csharp 讀取大文本文件數據到DataTable中,大批量插入到數據庫中
    csharp 在万年历中计算显示农历日子出错
    csharp create ICS file extension
    CSS DIV Shadow
    DataTable search keyword
    User select fontface/color/size/backgroundColor设置 字体,颜色,大小,背景色兼容主流浏览器
  • 原文地址:https://www.cnblogs.com/seyjs/p/10555758.html
Copyright © 2011-2022 走看看