- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1275-validate-binary-tree-nodes.kt
53 lines (43 loc) · 1.35 KB
/
1275-validate-binary-tree-nodes.kt
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
importjava.util.*
classSolution {
funvalidateBinaryTreeNodes(n:Int, leftChild:IntArray, rightChild:IntArray): Boolean {
val parents =IntArray(n) { -1 }
funbfsCheckCycle(start:Int): Boolean {
val queue:Queue<Int> =LinkedList()
queue.add(start)
parents[start] = start
while (queue.isNotEmpty()) {
val node = queue.poll()
listOf(
leftChild[node],
rightChild[node]
).forEach { next ->
if (next ==-1)
return@forEach
if (parents[next] == start)
returnfalse
if (parents[next] == next) {
parents[next] = start
return@forEach
}
parents[next] = start
queue.add(next)
}
}
returntrue
}
for (node in0 until n) {
if (parents[node] ==-1)
if (!bfsCheckCycle(node))
returnfalse
}
var count =0
for (i in0 until n) {
if (parents[i] == i)
++count
if (count >1)
returnfalse
}
return count ==1
}
}