-
Notifications
You must be signed in to change notification settings - Fork 0
/
124.go
68 lines (59 loc) · 1.23 KB
/
124.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
package p124
/**
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 must contain at least one node and does not need to go through the root.
For example:
Given the below binary tree,
1
/ \
2 3
Return 6.
*/
/**
* Definition for a binary tree node.
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func maxPathSum(root *TreeNode) int {
maxPath := 0
if root != nil {
maxPath = root.Val
}
max := func(a, b int) int {
if a > b {
return a
}
return b
}
var maxTraversal func(node *TreeNode) int
maxTraversal = func(node *TreeNode) int {
if node == nil {
return 0
}
left := maxTraversal(node.Left)
right := maxTraversal(node.Right)
singleHand := node.Val + max(left, right)
if left+right+node.Val > maxPath {
maxPath = left + right + node.Val
}
if singleHand > maxPath {
maxPath = singleHand
}
if node.Val > maxPath {
maxPath = node.Val
}
return max(singleHand, node.Val)
}
maxTraversal(root)
return maxPath
}