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.