Given a root node reference of a BST and a key, delete the node with the given key in the BST. Return the root node reference (possibly updated) of the BST.
Basically, the deletion can be divided into two stages:
Search for a node to remove
If the node is found, delete the node
There are three cases to consider when deleting a node:
Node has no children (leaf node): Simply remove it
Node has one child: Replace the node with its child
Node has two children: Replace the node with its inorder successor (or predecessor)
Input & Output
Example 1 — Node with Two Children
$Input:root = [5,3,6,2,4,null,7], key = 3
›Output:[5,4,6,2,null,null,7]
💡 Note:Node 3 has two children (2 and 4). Replace it with inorder successor 4, then delete original 4.
Example 2 — Leaf Node
$Input:root = [5,3,6,2,4,null,7], key = 2
›Output:[5,3,6,null,4,null,7]
💡 Note:Node 2 is a leaf node (no children), so simply remove it from the tree.
Example 3 — Root Node Deletion
$Input:root = [7], key = 7
›Output:[]
💡 Note:Deleting the only node in the tree results in an empty tree.
Constraints
The number of nodes in the tree is in the range [0, 104]
The optimal approach uses BST properties for efficient deletion with O(log n) time complexity. It handles three cases: leaf nodes (return null), single child (return the child), and two children (replace with inorder successor). This preserves tree structure while avoiding the overhead of complete reconstruction used by brute force methods.
Common Approaches
✓
BST Property Search with Recursive Deletion
⏱️ Time: O(log n)
Space: O(log n)
This optimal approach leverages BST properties to efficiently locate and delete the target node. It handles three cases: leaf nodes, nodes with one child, and nodes with two children using inorder successor replacement.
Brute Force Traversal
⏱️ Time: O(n)
Space: O(n)
This approach performs an inorder traversal to collect all values except the target key, then rebuilds a balanced BST from the sorted array. While conceptually simple, it doesn't leverage BST properties efficiently.
Hash-based Tree Reconstruction
⏱️ Time: O(n log n)
Space: O(n)
This approach uses a hash table to store all tree nodes, removes the target node, then reconstructs the BST from the remaining nodes. It provides O(1) lookup but requires rebuilding the entire tree structure.
BST Property Search with Recursive Deletion — Algorithm Steps
Use BST property to navigate: go left if key < node.val, right if key > node.val
Handle leaf node: simply return null to remove it
Handle one child: return the non-null child to replace current node
Handle two children: replace with inorder successor, then delete successor
Visualization
Tap to expand
Step-by-Step Walkthrough
1
Search Phase
Navigate BST: 3 < 5, go left. Found target node 3
2
Two Children Case
Node 3 has children 2 and 4. Find inorder successor (4)
3
Replace & Clean
Replace 3 with 4, then delete original 4 from right subtree
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode* createNode(int val) {
struct TreeNode* node = (struct TreeNode*)malloc(sizeof(struct TreeNode));
node->val = val;
node->left = NULL;
node->right = NULL;
return node;
}
struct TreeNode* solution(struct TreeNode* root, int key) {
if (root == NULL) return NULL;
if (key < root->val) {
root->left = solution(root->left, key);
} else if (key > root->val) {
root->right = solution(root->right, key);
} else {
// Node to delete found
if (root->left == NULL) {
return root->right;
} else if (root->right == NULL) {
return root->left;
} else {
// Node has two children - find inorder successor
struct TreeNode* minNode = root->right;
while (minNode->left != NULL) {
minNode = minNode->left;
}
root->val = minNode->val;
root->right = solution(root->right, minNode->val);
}
}
return root;
}
static int parseValues[10000];
static int isNullValues[10000];
int parseArray(char* data) {
int size = 0;
if (strcmp(data, "[]") == 0) return 0;
int len = strlen(data);
if (len < 2 || data[0] != '[' || data[len-1] != ']') return 0;
int i = 1;
while (i < len - 1) {
while (i < len - 1 && (data[i] == ' ' || data[i] == ',')) i++;
if (i >= len - 1) break;
if (data[i] == 'n' && strncmp(data + i, "null", 4) == 0) {
isNullValues[size] = 1;
parseValues[size] = 0;
i += 4;
} else {
isNullValues[size] = 0;
char* endptr;
parseValues[size] = (int)strtol(data + i, &endptr, 10);
i = endptr - data;
}
size++;
}
return size;
}
struct TreeNode* deserialize(char* data) {
int size = parseArray(data);
if (size == 0 || isNullValues[0]) return NULL;
struct TreeNode* root = createNode(parseValues[0]);
static struct TreeNode* queue[10000];
int front = 0, rear = 0;
queue[rear++] = root;
int i = 1;
while (front < rear && i < size) {
struct TreeNode* node = queue[front++];
if (i < size && !isNullValues[i]) {
node->left = createNode(parseValues[i]);
queue[rear++] = node->left;
}
i++;
if (i < size && !isNullValues[i]) {
node->right = createNode(parseValues[i]);
queue[rear++] = node->right;
}
i++;
}
return root;
}
void serialize(struct TreeNode* root, char* result) {
if (root == NULL) {
strcpy(result, "[]");
return;
}
static struct TreeNode* queue[10000];
static int values[10000];
static int isNull[10000];
int front = 0, rear = 0, size = 0;
queue[rear++] = root;
while (front < rear) {
struct TreeNode* node = queue[front++];
if (node != NULL) {
values[size] = node->val;
isNull[size] = 0;
queue[rear++] = node->left;
queue[rear++] = node->right;
} else {
isNull[size] = 1;
}
size++;
}
while (size > 0 && isNull[size-1]) size--;
strcpy(result, "[");
for (int i = 0; i < size; i++) {
if (i > 0) strcat(result, ",");
if (isNull[i]) {
strcat(result, "null");
} else {
char num[20];
sprintf(num, "%d", values[i]);
strcat(result, num);
}
}
strcat(result, "]");
}
int main() {
char rootInput[10000];
int key;
fgets(rootInput, sizeof(rootInput), stdin);
rootInput[strcspn(rootInput, "\n")] = 0;
scanf("%d", &key);
struct TreeNode* root = deserialize(rootInput);
struct TreeNode* result = solution(root, key);
char output[10000];
serialize(result, output);
printf("%s\n", output);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
O(log n)
Navigate tree height to find node, O(log n) average, O(n) worst case
n
2n
✓ Linear Growth
Space Complexity
O(log n)
Recursion stack depth equals tree height
n
2n
⚡ Linearithmic Space
87.7K Views
HighFrequency
~25 minAvg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.