zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):124-Binary Tree Maximum Path Sum

    题目来源:

      https://leetcode.com/problems/binary-tree-maximum-path-sum/


    题意分析:

      给定一棵树,找出一个数值最大的路径,起点可以是任意节点或者叶子。


    题目思路:

      我们可以先找路径的最大mr,ml,那么最大值是max(solve(root),solve(left),solve(right), max(mr + root.val + ml, root.val))。


    代码(python):

      

    # 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
            Solution.maxsum = root.val
            def solve(root):
                if root == None:
                    return 0
                sum,l,r = root.val,0,0
                if root.left:
                    l = solve(root.left)
                    if l > 0: sum += l
                if root.right:
                    r = solve(root.right)
                    if r > 0: sum += r
                Solution.maxsum = max(Solution.maxsum,sum)
                #print(Solution.maxsum)
                return max(root.val,max(root.val + l,root.val+r))
            solve(root)
            return Solution.maxsum
    View Code
  • 相关阅读:
    linux初始密码Mysql
    lamp整个打包
    模拟小球碰撞后返回
    Linux图形界面卡死
    非模态对话框
    菜单
    键盘消息简单示例
    菜单练习
    模态对话框练习
    阶段知识整合(画笔,画刷,字体)
  • 原文地址:https://www.cnblogs.com/chruny/p/5306285.html
Copyright © 2011-2022 走看看