URL: https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/ Signed-off-by: Matej Focko <me@mfocko.xyz>
28 lines
715 B
Kotlin
28 lines
715 B
Kotlin
class FindElements(root: TreeNode?) {
|
|
private val seen: MutableSet<Int> = mutableSetOf()
|
|
|
|
private fun bfs(root: TreeNode?) {
|
|
val q = ArrayDeque<TreeNode?>()
|
|
root?.`val` = 0
|
|
q.add(root)
|
|
|
|
while (q.isNotEmpty()) {
|
|
val node = q.removeFirst()
|
|
seen.add(node!!.`val`)
|
|
|
|
listOf(node?.left, node?.right)
|
|
.withIndex()
|
|
.filter { it.value != null }
|
|
.forEach { it ->
|
|
it.value?.`val` = node!!.`val` * 2 + 1 + it.index
|
|
q.add(it.value)
|
|
}
|
|
}
|
|
}
|
|
|
|
init {
|
|
bfs(root)
|
|
}
|
|
|
|
fun find(target: Int): Boolean = seen.contains(target)
|
|
}
|