-
Notifications
You must be signed in to change notification settings - Fork 0
/
110. Balanced Binary Tree.go
62 lines (46 loc) · 980 Bytes
/
110. Balanced Binary Tree.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
package main
import (
"fmt"
)
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func min(x, y int) int {
if x < y {
return x
}
return y
}
func max(x, y int) int {
if x > y {
return x
}
return y
}
func depthFirstTraversal(node *TreeNode, depth int) int {
if node == nil {
return depth
}
depth++
return max(depthFirstTraversal(node.Left, depth), depthFirstTraversal(node.Right, depth))
}
func checkValue(x, y int) bool {
return x == y || max(x, y)-min(x, y) == 1
}
func isBalanced(root *TreeNode) bool {
if root == nil {
return true
}
var leftHeight int = depthFirstTraversal(root.Left, 0)
var rightHeight int = depthFirstTraversal(root.Right, 0)
return checkValue(leftHeight, rightHeight) && isBalanced(root.Left) && isBalanced(root.Right)
}
func main() {
root := &TreeNode{1, nil, nil}
n2 := &TreeNode{2, nil, &TreeNode{3, nil, nil}}
root.Right = n2
answer := isBalanced(root)
fmt.Println("Answer is: ", answer)
}