-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdelete-node-in-bst.py
More file actions
27 lines (21 loc) · 1.01 KB
/
delete-node-in-bst.py
File metadata and controls
27 lines (21 loc) · 1.01 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
if not root: return None
if root.val < key: root.right = self.deleteNode(root.right, key)
elif root.val > key: root.left = self.deleteNode(root.left, key)
else:
if root.left == None and root.right == None: return None # doesn't have any children
if root.left == None and root.right: return root.right # has only right chilren
if root.right == None and root.left: return root.left # has only left children
# below is the case when it has both left and right children
curr = root.right
while curr.left:
curr = curr.left
root.val = curr.val
root.right = self.deleteNode(root.right, curr.val)
return root