Tensorum
LeetCode 450 · BST

Delete Node in a BST

LeetCode 450 · Medium · solution, intuition & step-by-step walkthrough

Replace with successor/predecessor, then delete that one.

MediumTreeBinary Search TreeBinary Tree
89 msruntime · beats 1%
59.7 MBmemory · beats 100%
1approach
2accepted runs · last 10 Jul 2024

This is how I solved Delete Node in a BST (LeetCode 450), a medium problem from the BST pattern. Below: the intuition, the approach step by step, my accepted Python code, animated test cases and a 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.

How I solved it

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
Loading the step-through…

Delete Node in a BST — FAQ

What is the intuition behind Delete Node in a BST?

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.

How do you solve 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.

What is the time and space complexity of Delete Node in a BST?

Time: O(h). Space: O(h). (Accepted approach: Successor / predecessor swap.)

What are common mistakes in Delete Node in a BST?

Reassign root.left / root.right with the recursive result.