-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path450_Delete_Node_in_a_BST.py
More file actions
34 lines (29 loc) · 1020 Bytes
/
Copy path450_Delete_Node_in_a_BST.py
File metadata and controls
34 lines (29 loc) · 1020 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
29
30
31
32
33
34
# 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 root == None:
return None
rootVal = root.val
if key < rootVal:
root.left = self.deleteNode(root.left, key)
elif key > rootVal:
root.right = self.deleteNode(root.right, key)
else:
if root.left == None:
return root.right
elif root.right == None:
return root.left
# find smallest on the right subtree
cur = root.right
minVal = cur.val
while(cur != None):
minVal = min(minVal, cur.val)
cur = cur.left
root.val = minVal
root.right = self.deleteNode(root.right, minVal)
return root