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
LeetCode இல் திற ↗

நான் 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.