-
Notifications
You must be signed in to change notification settings - Fork 0
/
110.go
61 lines (46 loc) · 848 Bytes
/
110.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
package main
import (
"fmt"
)
// Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// https://leetcode.com/problems/balanced-binary-tree/solutions/35686/java-solution-based-on-height-check-left-and-right-node-in-every-recursion-to-avoid-further-useless-search/
func max(a, b int) int {
if a > b {
return a
} else {
return b
}
}
func height(node *TreeNode) int {
if node == nil {
return 0
}
lH := height(node.Left)
if lH == -1 {
return -1
}
rH := height(node.Right)
if rH == -1 {
return -1
}
if lH-rH < -1 || lH-rH > 1 {
return -1
}
return max(lH, rH) + 1
}
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
return height(root) != -1
}
func main() {
tree := &TreeNode{0, nil, nil}
res := isBalanced(tree)
fmt.Println(res)
}