Delete Node in a BST
LeetCode 450 · మధ్యస్థం · పరిష్కారం, intuition & దశలవారీ వాక్త్రూ
Replace with successor/predecessor, then delete that one.
నేను Delete Node in a BST (LeetCode 450) ను ఇలా పరిష్కరించాను — BST ప్యాటర్న్లోని ఒక మధ్యస్థం ప్రాబ్లమ్. కింద: intuition, దశలవారీ approach, నా accepted Python కోడ్, animated test cases, line-by-line debugger.
కింది వివరణ ఇంగ్లీష్లో ఉంది.
Intuition
Find the node. A leaf can simply disappear. Otherwise replace its value with its in-order successor (smallest on the right) — or predecessor (largest on the left) if there's no right child — and delete that value from the subtree it came from.
Approach
- 1
Search left or right by comparing with key.
- 2
Leaf → None.
- 3
Has right child → copy successor's value, delete it from the right.
- 4
Else copy predecessor's value, delete it from the left.
నేను ఎలా పరిష్కరించాను
Successor / predecessor swapPythonO(h) time
class Solution:
def successor(self, node):
cur = node.right
while cur.left is not None:
cur = cur.left
return cur.val
def predecessor(self, node):
cur = node.left
while cur.right is not None:
cur = cur.right
return cur.val
def deleteNode(self, root, key):
if root is None:
return None
if key > root.val:
root.right = self.deleteNode(root.right, key)
elif key < root.val:
root.left = self.deleteNode(root.left, key)
else:
if root.left is None and root.right is None:
root = None
elif root.right is not None:
root.val = self.successor(root)
root.right = self.deleteNode(root.right, root.val)
else:
root.val = self.predecessor(root)
root.left = self.deleteNode(root.left, root.val)
return rootDelete Node in a BST — తరచూ అడిగే ప్రశ్నలు
Delete Node in a BST వెనుక ఉన్న intuition ఏమిటి?
Find the node. A leaf can simply disappear. Otherwise replace its value with its in-order successor (smallest on the right) — or predecessor (largest on the left) if there's no right child — and delete that value from the subtree it came from.
Delete Node in a BST (LeetCode 450) ను ఎలా పరిష్కరించాలి?
1. Search left or right by comparing with key. 2. Leaf → None. 3. Has right child → copy successor's value, delete it from the right. 4. Else copy predecessor's value, delete it from the left.
Delete Node in a BST యొక్క time, space complexity ఎంత?
Time: O(h). Space: O(h). (Accepted approach: Successor / predecessor swap.)
Delete Node in a BST లో సాధారణ పొరపాట్లు ఏమిటి?
Reassign root.left / root.right with the recursive result.