简繁EN

LeetCodeNo. 077

【LeetCode with Python】 124. Binary Tree Maximum Path Sum

目錄

題目

原題頁面:https://leetcode.com/problems/binary-tree-maximum-path-sum/
題目型別:Tree, Depth-first Search
難度評價:Hard
類似題目:(M) Path Sum, (M) Sum Root to Leaf Numbers

Given a 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 does not need to go through the root.

For example:
Given the below binary tree,

       1
      / \
     2   3

Return 6.


分析

本是比較簡單的一道二叉樹遞迴演算法題目,也花了一些時間。主要還是在題意的理解中,本題要求的“最大路徑和”,不一定經過了root,起點和終點可以是同一個點(即整個路徑只有一個點)。
注意用一個類成員變數max來記錄搜尋過程中出現過的最大路徑和,最後需要返回的就是這個max值。
此外還有一點容易搞錯,當一棵子樹計算完退棧時,向上一層返回的應該是該子樹左路徑、右路徑中的最大值,而不是該子樹中的“最大路徑和”,因為從父節點搜尋進入該子樹時,只能選擇其左分支或者右分治進入。
最後需要注意的一點是,這道題目並沒有說節點的值是正數或者自然數,考慮到leetcode一貫的尿性,最好認為負數也是會出現的。


程式碼

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Solution:
def __init__(self):
self.max = None

def doMaxPathSum(self, root):
if None == root:
return 0
left_sum = self.doMaxPathSum(root.left)
right_sum = self.doMaxPathSum(root.right)
max_left_sum = max(left_sum, 0)
max_right_sum = max(right_sum, 0)
cur_max = max_left_sum + max_right_sum + root.val
if None == self.max or cur_max > self.max:
self.max = cur_max
return max(max_left_sum + root.val, max_right_sum + root.val)

# @param root, a tree node
# @return an integer
def maxPathSum(self, root):
self.max = None
self.doMaxPathSum(root)
return self.max

本文地址:https://xnerv.wang/zh-tw/leetcode-binary-tree-maximum-path-sum/