Delete Node in a BST (LeetCode 450): Solution and Explanation
Given the root of a binary search tree and a key, remove the node holding that key if it exists and return the root of the updated tree. The tree must still be a valid BST afterwards.
Intuition
Finding the node is ordinary BST search: compare the key with the current value and go left or right. Writing it recursively, where each call returns the new root of its subtree, makes the removal easy, because the parent just assigns the returned pointer back to root.left or root.right.
If the node has no left child, its right child (possibly null) can take its place directly. Every value in that right subtree already sits on the correct side of every ancestor. The same goes for a node with no right child and its left subtree.
The interesting case is a node with two children. We cannot lift both subtrees into one slot. Instead we keep the node where it is and change its value to the next larger value in the tree, its in-order successor. That successor is the leftmost node of the right subtree, so it is larger than everything on the left and smaller than everything else on the right. After copying, the successor's old node is a duplicate, and since it has no left child it is easy to delete with the same function.
Using the in-order predecessor (the largest value in the left subtree) works just as well and produces a different valid tree. This page uses the successor, and the judge accepts either tree.
Approach: Recursive delete with the in-order successor
- If
rootis null, the key is not in this subtree. Return null. - If
key < root.val, setroot.left = deleteNode(root.left, key). Ifkey > root.val, setroot.right = deleteNode(root.right, key). - Otherwise
rootholds the key. Ifroot.leftis null returnroot.right, and ifroot.rightis null returnroot.left. - With two children, set
succ = root.rightand movesucc = succ.leftuntil it has no left child. - Copy
succ.valintoroot, then setroot.right = deleteNode(root.right, succ.val). - Return
root.
Step-by-step example
root = [5,3,6,2,4,null,7], key = 3
- At 5, the key 3 is smaller, so recurse into the left child.
- At 3, the key matches. Node 3 has both children, 2 and 4.
- The successor search starts at the right child 4. It has no left child, so 4 is the successor.
- Copy 4 into the node that held 3. The tree now holds 4 twice.
- Delete 4 from the right subtree of the copied node. That old 4 is a leaf, so the call returns null and the node's right pointer becomes null.
- The calls return back up and the root 5 is returned: [5,4,6,2,null,null,7].
Code: Python, Java, C++
1class Solution:
2 def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
3 if not root:
4 return None
5 if key < root.val:
6 root.left = self.deleteNode(root.left, key)
7 elif key > root.val:
8 root.right = self.deleteNode(root.right, key)
9 else:
10 if not root.left:
11 return root.right
12 if not root.right:
13 return root.left
14 succ = root.right
15 while succ.left:
16 succ = succ.left
17 root.val = succ.val
18 root.right = self.deleteNode(root.right, succ.val)
19 return root1class Solution {
2 public TreeNode deleteNode(TreeNode root, int key) {
3 if (root == null) return null;
4 if (key < root.val) {
5 root.left = deleteNode(root.left, key);
6 } else if (key > root.val) {
7 root.right = deleteNode(root.right, key);
8 } else {
9 if (root.left == null) return root.right;
10 if (root.right == null) return root.left;
11 TreeNode succ = root.right;
12 while (succ.left != null) {
13 succ = succ.left;
14 }
15 root.val = succ.val;
16 root.right = deleteNode(root.right, succ.val);
17 }
18 return root;
19 }
20}1class Solution {
2public:
3 TreeNode* deleteNode(TreeNode* root, int key) {
4 if (!root) return nullptr;
5 if (key < root->val) {
6 root->left = deleteNode(root->left, key);
7 } else if (key > root->val) {
8 root->right = deleteNode(root->right, key);
9 } else {
10 if (!root->left) return root->right;
11 if (!root->right) return root->left;
12 TreeNode* succ = root->right;
13 while (succ->left) {
14 succ = succ->left;
15 }
16 root->val = succ->val;
17 root->right = deleteNode(root->right, succ->val);
18 }
19 return root;
20 }
21};Time and space complexity
O(h)
The search walks one root-to-node path, and the successor search plus the second delete continue down the same subtree, so the work is proportional to the height h. That is O(log n) for a balanced tree and O(n) for a skewed one.
O(h)
The recursion stack holds at most one frame per level of the tree.
Other approaches
In-order predecessor (time O(h), space O(h))
Replace the value with the largest value of the left subtree instead and delete that node from the left. It is equally correct and gives a different tree, which the judge also accepts.
Iterative with parent pointer (time O(h), space O(1))
Search with a loop while tracking the parent, then splice by rewiring the parent's pointer. It avoids recursion but has more special cases, especially when the root itself is deleted.
Common mistakes
- Forgetting to assign the result of the recursive call back to
root.leftorroot.right. The splice then never reaches the parent. - Moving the successor node itself without removing it from its old place, which leaves a cycle or a duplicate value.
- Looking for the successor in the left subtree, or going right repeatedly instead of right once and then left.
- Returning the original root when the root itself was a leaf or had one child. The recursive return value already handles that case.
Frequently asked questions
Why does the in-order successor keep the tree valid?
It is the smallest value in the right subtree, so it is larger than everything in the left subtree and no larger than anything else on the right. Placing it in the deleted node's slot keeps both sides in order.
Why is deleting the successor afterwards easy?
The successor is the leftmost node of the right subtree, so it has no left child. Deleting it hits the one-child or no-child case and never needs another successor search.
What happens if the key is not in the tree?
The search reaches a null child, that call returns null, and every parent reassigns the same pointer it already had. The tree is returned unchanged.
Could I use the predecessor instead?
Both are accepted. The judge checks that your tree is a valid BST holding exactly the original values minus the key, so the predecessor version passes too.