-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
111 lines (90 loc) · 1.51 KB
/
main.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package main
func main() {
}
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
func isCompleteTree(root *TreeNode) bool {
if isLeaf(root) {
return true
}
return isComplete(root)
}
func isComplete(root *TreeNode) bool {
q := []*TreeNode{root}
var (
count int
prevLastArr []*TreeNode
)
if isLeaf(root.Left) {
count++
}
if isLeaf(root.Right) {
count++
}
for len(q) != 0 {
size := len(q)
count = 0
prevLastArr = q
isFull := true
for i := 0; i < size; i++ {
n := q[0]
q = q[1:]
if isLeaf(n.Left) {
count++
}
if isLeaf(n.Right) {
count++
}
if n.Left != nil {
q = append(q, n.Left)
} else if n.Left == nil {
isFull = false
}
if n.Right != nil {
q = append(q, n.Right)
} else {
isFull = false
}
}
isPreLast := count == size*2
// fmt.Println(isPreLast, count, size, prevLastArr[0].Val)
if isPreLast {
break
}
if count == size*2 {
isPreLast = true
}
// fmt.Println(len(q), isFull)
if len(q) != 0 && !isFull {
return false
}
}
var lastArr []*TreeNode
for _, v := range prevLastArr {
lastArr = append(lastArr, v.Left)
lastArr = append(lastArr, v.Right)
}
return isLeft(lastArr)
}
func isLeaf(n *TreeNode) bool {
return n == nil || (n.Left == nil && n.Right == nil)
}
func isLeft(arr []*TreeNode) bool {
var (
between bool
)
for _, v := range arr {
if v == nil {
between = true
continue
}
if v != nil && between {
return false
}
between = false
}
return true
}