kt: add «1261. Find Elements in a Contaminated Binary Tree»

URL:	https://leetcode.com/problems/find-elements-in-a-contaminated-binary-tree/
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2025-02-21 15:13:26 +01:00
parent 1c60b8cabd
commit 359ff970a5
Signed by: mfocko
SSH key fingerprint: SHA256:icm0fIOSJUpy5+1x23sfr+hLtF9UhY8VpMC7H4WFJP8

View file

@ -0,0 +1,28 @@
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)
}