[leetcode]Binary Tree Maximum Path Sum @ Python


原題地址:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

題意:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example:
Given the below binary tree,

       1
      / \
     2   3

 

Return 6.

解題思路:這道題是在樹中尋找一條路徑,這條路徑上的節點的和為最大,起點和終點只要是樹里面的節點就可以了。這里需要注意的一點是:節點值有可能為負值。解決這道二叉樹的題目還是來使用遞歸。例如下面這棵樹:

            1

             /     \

           2        3

            /    \    /    \

         4     5  6     7

對於這棵樹而言,和為最大的路徑為:5->2->1->3->7。

那么這條路徑是怎么求出來的呢?這里需要用到一個全局變量Solution.max,可以隨時被更大的路徑和替換掉。在函數遞歸到左子樹時:最大的路徑為:4->2->5。但此時函數的返回值應當為4->2和5->2這兩條路徑中和最大的一條。右子樹同理。而Solution.max用來監控每個子樹中的最大路徑和。那么思路就是:(左子樹中的最大路徑和,右子樹中的最大路徑和,以及左子樹中以root.left為起點的最大路徑(需要大於零)+右子樹中以root.right為起點的最大路徑(需要大於零)+root.val),這三者中的最大值就是最大的路徑和。

代碼:

# Definition for a  binary tree node
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    # @param root, a tree node
    # @return an integer
    def maxsum(self, root):
        if root == None: return 0
        sum = root.val
        lmax = 0; rmax = 0
        if root.left:
            lmax = self.maxsum(root.left)
            if lmax > 0:
                sum += lmax
        if root.right:
            rmax = self.maxsum(root.right)
            if rmax > 0:
                sum += rmax
        if sum > Solution.max: Solution.max = sum
        return max(root.val, max(root.val + lmax, root.val + rmax))
    
    def maxPathSum(self, root):
        Solution.max = -10000000
        if root == None: return 0
        self.maxsum(root)
        return Solution.max

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM