Skip to content

Commit f360496

Browse files
authored
Create 0450-delete-node-in-a-bst.py
1 parent 24964c1 commit f360496

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

python/0450-delete-node-in-a-bst.py

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Definition for a binary tree node.
2+
# class TreeNode:
3+
# def __init__(self, val=0, left=None, right=None):
4+
# self.val = val
5+
# self.left = left
6+
# self.right = right
7+
class Solution:
8+
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
9+
if not root:
10+
return root
11+
12+
if key > root.val:
13+
root.right = self.deleteNode(root.right, key)
14+
elif key < root.val:
15+
root.left = self.deleteNode(root.left, key)
16+
else:
17+
if not root.left:
18+
return root.right
19+
elif not root.right:
20+
return root.left
21+
22+
# Find the min from right subtree
23+
cur = root.right
24+
while cur.left:
25+
cur = cur.left
26+
root.val = cur.val
27+
root.right = self.deleteNode(root.right, root.val)
28+
return root

0 commit comments

Comments
 (0)