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:
parent
1c60b8cabd
commit
359ff970a5
1 changed files with 28 additions and 0 deletions
28
kt/find-elements-in-a-contaminated-binary-tree.kt
Normal file
28
kt/find-elements-in-a-contaminated-binary-tree.kt
Normal 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)
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue