-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDelete_Node.py
More file actions
32 lines (29 loc) · 1 KB
/
Delete_Node.py
File metadata and controls
32 lines (29 loc) · 1 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
28
29
30
31
32
# 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 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 not root.left:
return root.right
elif not root.right:
return root.left
else:
successor = self.getSuccessor(root.right)
root.val = successor.val
root.right = self.deleteNode(root.right, successor.val)
return root
def getSuccessor(self, node):
curr = node
while curr.left:
curr = curr.left
return curr