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
.
求樹的最大路徑和~這裏路徑可以起始和終結於任意節點~這種題還是不太會,不知道怎麼寫,看了別人的答案才寫出來的~一個結點自身的最長路徑就是它的左子樹返回值(如果大於0的話),加上右子樹的返回值(如果大於0的話),再加上自己的值。而返回值則是自己的值加上左子樹返回值,右子樹返回值或者0~在過程中求得當前最長路徑時比較一下是不是目前最長的,如果是則更新~感覺這題比較有技巧性,希望自己下次看到能再寫出來~
class Solution:
# @param root, a tree node
# @return an integer
def maxPathSum(self, root):
if root is None: return 0
self.res = - (1 << 31) #-2147483648
self.helper(root)
return self.res
def helper(self, root):
if root is None: return 0
left = max(0, self.helper(root.left))
right = max(0, self.helper(root.right))
self.res = max(self.res, root.val + left + right)
return root.val + max(left, right)