-
Notifications
You must be signed in to change notification settings - Fork 2.5k
Expand file tree
/
Copy path0450-delete-node-in-a-bst.py
More file actions
28 lines (26 loc) · 922 Bytes
/
0450-delete-node-in-a-bst.py
File metadata and controls
28 lines (26 loc) · 922 Bytes
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
28
# Definition for a binary tree node.
# 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 root
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(root.left, key)
else:
if not root.left:
return root.right
elif not root.right:
return root.left
# Find the min from right subtree
cur = root.right
while cur.left:
cur = cur.left
root.val = cur.val
root.right = self.deleteNode(root.right, root.val)
return root