Created
November 22, 2021 18:03
-
-
Save ssshukla26/51e083b1ec5708f91a52acf14fa86a2c to your computer and use it in GitHub Desktop.
Delete Node from a BST [LeetCode 450]
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 deleteAndReplaceWithMin(self, root: TreeNode): | |
# Find minimum from the right subtree | |
curr = root.right | |
while curr.left: | |
curr = curr.left | |
# Remove the current from right subtree | |
root.right = self.deleteNode(root.right, curr.val) | |
# Replace the root val | |
root.val = curr.val | |
return | |
def deleteAndReplaceWithMax(self, root: TreeNode): | |
# Find maximum from the left subtree | |
curr = root.left | |
while curr.right: | |
curr = curr.right | |
# Remove the current from left subtree | |
root.left = self.deleteNode(root.left, curr.val) | |
# Replace the root val | |
root.val = curr.val | |
return | |
def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]: | |
if root: | |
if key < root.val: | |
root.left = self.deleteNode(root.left, key) | |
elif key > root.val: | |
root.right = self.deleteNode(root.right, key) | |
else: | |
# Remove leaf and nothing changes | |
if not root.left and not root.right: | |
root = None | |
# Remove a node with only one child, in this point the parent of node to that child | |
elif not root.left: | |
root = root.right | |
elif not root.right: | |
root = root.left | |
# Remove a node with two children, either replace the node with minimum from right | |
# subtree or replace the node with maximum of left subtree. | |
else: | |
self.deleteAndReplaceWithMin(root) # self.deleteAndReplaceWithMax(root) | |
return root |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment