kt: add «1325. Delete Leaves With a Given Value»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
5bdc00e5ca
commit
04c2005f8a
1 changed files with 28 additions and 0 deletions
28
kt/delete-leaves-with-a-given-value.kt
Normal file
28
kt/delete-leaves-with-a-given-value.kt
Normal file
|
@ -0,0 +1,28 @@
|
||||||
|
class TreeNode(var `val`: Int) {
|
||||||
|
var left: TreeNode? = null
|
||||||
|
var right: TreeNode? = null
|
||||||
|
}
|
||||||
|
|
||||||
|
class Solution {
|
||||||
|
fun isLeaf(node: TreeNode?): Boolean {
|
||||||
|
return node != null && node.left == null && node.right == null
|
||||||
|
}
|
||||||
|
|
||||||
|
fun removeLeafNodes(
|
||||||
|
root: TreeNode?,
|
||||||
|
target: Int,
|
||||||
|
): TreeNode? {
|
||||||
|
if (root == null) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
root.left = removeLeafNodes(root.left, target)
|
||||||
|
root.right = removeLeafNodes(root.right, target)
|
||||||
|
|
||||||
|
if (isLeaf(root) && root.`val` == target) {
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
return root
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue