Skip to content

Commit 2e4dba0

Browse files
authored
Create 1361-validate-binary-tree-nodes.kt
1 parent dbae42b commit 2e4dba0

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
class Solution {
2+
fun validateBinaryTreeNodes(n: Int, leftChild: IntArray, rightChild: IntArray): Boolean {
3+
val hasParent = hashSetOf<Int>().apply {
4+
for (n in (leftChild + rightChild)) {
5+
if (n != -1)
6+
this.add(n)
7+
}
8+
}
9+
10+
if (hasParent.size == n) return false
11+
12+
var root = -1
13+
for (i in 0 until n) {
14+
if (i !in hasParent) {
15+
root = i
16+
break
17+
}
18+
}
19+
20+
val visit = hashSetOf<Int>()
21+
fun dfs(i: Int): Boolean {
22+
if (i == -1) return true
23+
if (i in visit) return false
24+
25+
visit.add(i)
26+
27+
return dfs(leftChild[i]) && dfs(rightChild[i])
28+
}
29+
30+
return dfs(root) && visit.size == n
31+
}
32+
}

0 commit comments

Comments
 (0)