Tensorum
YouTubeसीखना शुरू करें
LeetCode 450 · BST

Delete Node in a BST

LeetCode 450 · मध्यम · समाधान, intuition और कदम-दर-कदम वॉकथ्रू

Replace with successor/predecessor, then delete that one.

मध्यमTreeBinary Search TreeBinary Tree

मैंने 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. 1

    Search left or right by comparing with key.

  2. 2

    Leaf → None.

  3. 3

    Has right child → copy successor's value, delete it from the right.

  4. 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 root
स्टेप-थ्रू लोड हो रहा है…

Delete 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.