Skip to content

Commit 3780328

Browse files
aQuaaQua
aQua
authored and
aQua
committed
124 accepted. 43ms.
1 parent 99280a3 commit 3780328

File tree

2 files changed

+20
-27
lines changed

2 files changed

+20
-27
lines changed

Algorithms/0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum.go

Lines changed: 14 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -8,44 +8,31 @@ type TreeNode = kit.TreeNode
88

99
func maxPathSum(root *TreeNode) int {
1010
if root == nil {
11-
return -1<<31
11+
return 0
1212
}
1313

14-
sum := root.Val +
15-
max(0, maxSince(root.Left)) +
16-
max(0, maxSince(root.Right))
17-
18-
return max(
19-
sum,
20-
max(
21-
maxPathSum(root.Left),
22-
maxPathSum(root.Right),
23-
),
24-
)
25-
}
26-
27-
// 返回,从 root 出发,包含 root 在内的所有可能路径的最大的 sum 值
28-
func maxSince(root *TreeNode) int {
29-
res := -1 << 31
14+
maxSum := root.Val
3015

31-
var dfs func(*TreeNode, int)
32-
dfs = func(root *TreeNode, sum int) {
16+
// 返回,从 root 出发,包含 root 在内的所有可能路径的最大的 sum 值
17+
var dfs func(*TreeNode) int
18+
dfs = func(root *TreeNode) int {
3319
if root == nil {
34-
return
20+
return 0
3521
}
3622

37-
sum += root.Val
38-
if res < sum {
39-
res = sum
23+
left := max(0, dfs(root.Left))
24+
right := max(0, dfs(root.Right))
25+
sum := left + root.Val + right
26+
if maxSum < sum {
27+
maxSum = sum
4028
}
4129

42-
dfs(root.Left, sum)
43-
dfs(root.Right, sum)
30+
return max(left, right) + root.Val
4431
}
4532

46-
dfs(root, 0)
33+
dfs(root)
4734

48-
return res
35+
return maxSum
4936
}
5037

5138
func max(a, b int) int {

Algorithms/0124.binary-tree-maximum-path-sum/binary-tree-maximum-path-sum_test.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,12 @@ func Test_Problem0124(t *testing.T) {
1818
ans int
1919
}{
2020

21+
{
22+
[]int{},
23+
[]int{},
24+
0,
25+
},
26+
2127
{
2228
[]int{-10, 100, -1, -2},
2329
[]int{-10, -1, 100, -2},

0 commit comments

Comments
 (0)