-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
63 lines (55 loc) · 755 Bytes
/
main.go
File metadata and controls
63 lines (55 loc) · 755 Bytes
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
package main
import (
"log"
"math"
)
// Tree Node
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
/*
*
*
* is Balanced
*
* args :
* root *TreeNode
*
* return value:
* bool
*
*
*/
func isBalanced(root *TreeNode) bool {
var f func(r *TreeNode) int
f = func(r *TreeNode) int {
if r == nil {
return 0
}
lh := f(r.Left)
if lh == -1 {
return -1
}
rh := f(r.Right)
if rh == -1 {
return -1
}
if int(math.Abs(float64(lh-rh))) > 1 {
return -1
}
if rh > lh {
return rh + 1
}
return lh + 1
}
return f(root) > -1
}
func main() {
// simple test
if ans := isBalanced(nil); !ans {
log.Fatalf("Worn Answer! answer equal `True` not equal : %v", ans)
}
log.Println("Answer is True!")
}