Skip to content

Commit 837222b

Browse files
committed
binary_tree_maximum_path_sum
1 parent b02ec07 commit 837222b

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
107107
#### [118. pascal's triangle](https://github.com/hitzzc/go-leetcode/tree/master/pascals_triangle)
108108
#### [119. pascal's triangle II](https://github.com/hitzzc/go-leetcode/tree/master/pascals_triangle_II)
109109
#### [120. triangle](https://github.com/hitzzc/go-leetcode/tree/master/triangle)
110+
#### [124. binary tree maximum path sum](https://github.com/hitzzc/go-leetcode/tree/master/binary_tree_maximum_path_sum)
110111
#### [125. valid palindrome](https://github.com/hitzzc/go-leetcode/tree/master/valid_palindrome)
111112

112113

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package binary_tree_maximum_path_sum
2+
3+
type TreeNode struct {
4+
Val int
5+
Left *TreeNode
6+
Right *TreeNode
7+
}
8+
9+
type solution struct {
10+
max int
11+
first bool
12+
}
13+
14+
func maxPathSum(root *TreeNode) int {
15+
s := &solution{first: true}
16+
s.helper(root)
17+
return s.max
18+
}
19+
20+
func (this *solution) helper(root *TreeNode) (max int) {
21+
if root == nil {
22+
return 0
23+
}
24+
tmp := root.Val
25+
left := this.helper(root.Left)
26+
if left > 0 {
27+
tmp += left
28+
}
29+
right := this.helper(root.Right)
30+
if right > 0 {
31+
tmp += right
32+
}
33+
if this.first || tmp > this.max {
34+
this.first = false
35+
this.max = tmp
36+
}
37+
if left > 0 && left > right {
38+
max = root.Val + left
39+
} else if right > 0 && right > left {
40+
max = root.Val + right
41+
} else {
42+
max = root.Val
43+
}
44+
return
45+
}

0 commit comments

Comments
 (0)