forked from luliyucoordinate/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1373.go
44 lines (38 loc) · 744 Bytes
/
1373.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
var maxv int
func maxSumBST(root *TreeNode) int {
maxv = 0
dfs(root)
return maxv
}
func dfs(root *TreeNode) (bool, int) {
if root == nil {
return true, 0
}
reb, rev := true, root.Val
if root.Left != nil {
ok, l := dfs(root.Left)
if ok && root.Left.Val < root.Val {
rev += l
} else {
reb = false
}
}
if root.Right != nil {
ok, r := dfs(root.Right)
if ok && root.Right.Val > root.Val {
rev += r
} else {
reb = false
}
}
if reb {
maxv = max(maxv, rev)
}
return reb, rev
}
func max(a, b int) int {
if a > b {
return a
}
return b
}