124. Binary Tree Maximum Path Sum

time: O(n)

space: O(H), where H is a tree height, to keep the recursion stack.

計算子樹在一一合併, 左右根 post order

這題主要是要想到可以捨棄負的節點, 丟掉負的絕對比較能得到最大的結果

還有 res 是獨立計算的

why do this?

ex: input: [2,-1], ans = 2

if we don't max with 0

at last, res = 2-1 = 1

return Math.max(-1, 0) + 2 = 1

ans = 1, it's wrong, so when cal left, right result, we should compare with 0, then it's the max value

without global variable

use int[] , it can be a memory

why return Math.max(left, right) + node.val;? -> for func_max路徑

結論,

求兩個東西

1.也就是我們求一個 max down path sum (func_max路徑)

  1. 那有這個路徑, 之後就是拿來算 max path sum (拐點value + func_max路徑(left node) + func_max路徑(right node))

會是我們的答案, 因為 math path = 拐點 + 左右path max sum (只有一個拐點喔!

Last updated

Was this helpful?