Skip to content

Commit f2fe500

Browse files
authored
Create 0450-delete-node-in-a-bst.kt
1 parent 5a6ed05 commit f2fe500

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

kotlin/0450-delete-node-in-a-bst.kt

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Example:
3+
* var ti = TreeNode(5)
4+
* var v = ti.`val`
5+
* Definition for a binary tree node.
6+
* class TreeNode(var `val`: Int) {
7+
* var left: TreeNode? = null
8+
* var right: TreeNode? = null
9+
* }
10+
*/
11+
12+
//recursive solution
13+
class Solution {
14+
fun deleteNode(root: TreeNode?, key: Int): TreeNode? {
15+
16+
root?: return null
17+
18+
if (root.value < key) {
19+
root.right = deleteNode(root.right, key)
20+
} else if (root.value > key) {
21+
root.left = deleteNode(root.left, key)
22+
} else {
23+
if (root.right == null) return root.left
24+
if (root.left == null) return root.right
25+
26+
var current = root.right
27+
while (current.left != null) current = current.left
28+
root.`val` = current.value
29+
root.right = deleteNode(root.right, root.value)
30+
}
31+
32+
return root
33+
}
34+
35+
private val TreeNode.value get() = `val`
36+
}

0 commit comments

Comments
 (0)