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.