-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathsolution.go
More file actions
48 lines (39 loc) · 753 Bytes
/
solution.go
File metadata and controls
48 lines (39 loc) · 753 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
package main
import "fmt"
// TreeNode is a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
// IsBalanced check if TreeNode is balanced
var IsBalanced bool
func isBalanced(root *TreeNode) bool {
IsBalanced = true
getHeight(root)
return IsBalanced
}
func abs(x int) int {
if x < 0 {
return -x
}
return x
}
func getHeight(root *TreeNode) int {
if root == nil {
return 0
}
left := getHeight(root.Left)
right := getHeight(root.Right)
if abs(left-right) > 1 {
IsBalanced = false
}
if left > right {
return left + 1
}
return right + 1
}
func main() {
t := &TreeNode{3, &TreeNode{9, nil, nil}, &TreeNode{20, &TreeNode{15, nil, nil}, &TreeNode{7, nil, nil}}}
fmt.Println(isBalanced(t))
}