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.