題目
原題頁面: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 3Return
6.
分析
本是比較簡單的一道二叉樹遞迴演算法題目,也花了一些時間。主要還是在題意的理解中,本題要求的“最大路徑和”,不一定經過了root,起點和終點可以是同一個點(即整個路徑只有一個點)。
注意用一個類成員變數max來記錄搜尋過程中出現過的最大路徑和,最後需要返回的就是這個max值。
此外還有一點容易搞錯,當一棵子樹計算完退棧時,向上一層返回的應該是該子樹左路徑、右路徑中的最大值,而不是該子樹中的“最大路徑和”,因為從父節點搜尋進入該子樹時,只能選擇其左分支或者右分治進入。
最後需要注意的一點是,這道題目並沒有說節點的值是正數或者自然數,考慮到leetcode一貫的尿性,最好認為負數也是會出現的。
程式碼
1 | class Solution: |
本文地址:https://xnerv.wang/zh-tw/leetcode-binary-tree-maximum-path-sum/
