Skip to content

Commit cc55bfb

Browse files
aQuaaQua
authored andcommitted
124 ut pass
1 parent edf663d commit cc55bfb

File tree

2 files changed

+42
-12
lines changed

2 files changed

+42
-12
lines changed

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

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,25 +3,49 @@ package Problem0124
33
import (
44
"github.com/aQuaYi/LeetCode-in-Golang/kit"
55
)
6+
67
type TreeNode = kit.TreeNode
78

89
func maxPathSum(root *TreeNode) int {
9-
res := -1<<31
10-
if root == nil {
11-
return res
12-
}
10+
if root == nil {
11+
return -1<<31
12+
}
1313

14+
sum := root.Val +
15+
max(0, maxSince(root.Left)) +
16+
max(0, maxSince(root.Right))
1417

15-
return res
18+
return max(sum,
19+
max(maxPathSum(root.Left), maxPathSum(root.Right)))
1620
}
1721

18-
func maxRoot2Leaf() {
19-
22+
// 返回,从 root 出发,包含 root 在内的所有可能路径的最大的 sum 值
23+
func maxSince(root *TreeNode) int {
24+
res := -1 << 31
25+
26+
var dfs func(*TreeNode, int)
27+
dfs = func(root *TreeNode, sum int) {
28+
if root == nil {
29+
return
30+
}
31+
32+
sum += root.Val
33+
if res < sum {
34+
res = sum
35+
}
36+
37+
dfs(root.Left, sum)
38+
dfs(root.Right, sum)
39+
}
40+
41+
dfs(root, 0)
42+
43+
return res
2044
}
2145

22-
func max(a, b int ) int {
23-
if a> b {
24-
return a
46+
func max(a, b int) int {
47+
if a > b {
48+
return a
2549
}
26-
return b
27-
}
50+
return b
51+
}

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{-10, 100, -1, -2},
23+
[]int{-10, -1, 100, -2},
24+
100,
25+
},
26+
2127
{
2228
[]int{10, 10, -1, -2},
2329
[]int{10, -1, 10, -2},

0 commit comments

Comments
 (0)