Delete Node in a BST
Problem Statement
You are given the root of a binary search tree and a key.
Delete the node that holds key, then return the root of the tree. The tree must still be a valid BST. If key is not in the tree, the values stay the same. When the deleted node has two children, more than one shape can be correct, so any valid answer is accepted.
The root of a binary search tree (between 0 and 10^4 nodes, all values unique), and an integer key.
The root of a valid BST that holds the same values as before, minus key.
The node 3 has two children. Its inorder successor is 4, the smallest value bigger than 3. Copy 4 into that node, then remove the old 4. [5, 2, 6, null, 4, null, 7] is also accepted.
No node holds 0, so nothing changes.
An empty tree stays empty.
- β’ The number of nodes is between 0 and 10^4
- β’ β10^5 β€ Node.val β€ 10^5
- β’ Each node value is unique
- β’ root is a valid binary search tree
- β’ β10^5 β€ key β€ 10^5
- β’ Follow-up: can you do it in O(height of the tree) time?
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
Inorder list of the same node objects, drop the key's node, then relink them into a balanced BST
Find the key by comparing, then handle 0, 1 or 2 children; with 2 children, copy the successor up and delete it below
Walk the tree in order to collect the nodes. Remove the node whose value is key. Then rebuild a balanced BST from the sorted nodes that are left, changing only their child pointers. No new nodes are created, but every node is relinked, even the ones far from key.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree DFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.