Practice › Trees
Delete a Node from a BST
Medium · Trees · Asked at Amazon, Microsoft, Uber, Oracle
Delete the node with value key from the binary search tree (if key is not in the tree, nothing changes) and print the resulting tree, or EMPTY if the tree becomes empty. Use this rule:
- A node with no children is simply removed.
- A node with one child is replaced by that child.
- A node with two children takes the value of its in-order successor (the smallest value in its right subtree), and that successor node is then deleted from the right subtree.
Input
First line: k. Second line: k values — the tree in level order, -1 means no node. Third line: key.
Output
The tree in the same level-order format on one line (-1 for missing children, trailing -1s removed). Or EMPTY.
Constraints
- 1 ≤ number of nodes ≤ 10^4
- all values are distinct and positive
Write it recursively: delete(node, key) returns the new root of that subtree. The successor is found by going right once and then left as far as possible.
Example 1
Input
7 5 3 6 2 4 -1 7 3
Output
5 4 6 2 -1 -1 7
Example 2
Input
7 5 3 6 2 4 -1 7 0
Output
5 3 6 2 4 -1 7
Hints
- First find the node with a normal BST search.
- Zero or one child: replace the node by that child (or by nothing).
- Two children: copy in the smallest value of the right subtree, then delete that value from the right subtree.
Approach
Recursive deleteNode(node, key) returns the new root of the subtree. If key is smaller, recurse left; larger, recurse right. On a match with at most one child, return the other child. With two children, the in-order successor (go right once, then left as far as possible) has no left child, so after copying its value into the node, deleting it from the right subtree is the easy case. Print EMPTY if the tree becomes empty.
Complexity: O(h) time for the delete · O(n) to read and print
Solution
C++ solution
#include <bits/stdc++.h>
using namespace std;
struct Node {
long long val;
Node *left = nullptr, *right = nullptr;
Node(long long v) : val(v) {}
};
// level order with -1 for a missing child
Node *build(const vector<long long> &a) {
if (a.empty() || a[0] == -1) return nullptr;
Node *root = new Node(a[0]);
queue<Node *> q;
q.push(root);
size_t i = 1;
while (!q.empty() && i < a.size()) {
Node *cur = q.front();
q.pop();
if (i < a.size() && a[i] != -1) q.push(cur->left = new Node(a[i]));
i++;
if (i < a.size() && a[i] != -1) q.push(cur->right = new Node(a[i]));
i++;
}
return root;
}
vector<long long> readTree() {
int k;
cin >> k;
vector<long long> a(k);
for (auto &x : a) cin >> x;
return a;
}
string serialize(Node *root) {
vector<long long> out;
queue<Node *> q;
q.push(root);
while (!q.empty()) {
Node *n = q.front();
q.pop();
if (!n) {
out.push_back(-1);
continue;
}
out.push_back(n->val);
q.push(n->left);
q.push(n->right);
}
while (!out.empty() && out.back() == -1) out.pop_back();
string s;
for (size_t i = 0; i < out.size(); i++) s += (i ? " " : "") + to_string(out[i]);
return s;
}
Node *deleteNode(Node *n, long long key) {
if (!n) return nullptr;
if (key < n->val) n->left = deleteNode(n->left, key);
else if (key > n->val) n->right = deleteNode(n->right, key);
else {
if (!n->left) return n->right;
if (!n->right) return n->left;
Node *m = n->right;
while (m->left) m = m->left;
n->val = m->val;
n->right = deleteNode(n->right, m->val);
}
return n;
}
int main() {
Node *root = build(readTree());
long long key;
cin >> key;
root = deleteNode(root, key);
cout << (root ? serialize(root) : "EMPTY") << "\n";
return 0;
}Python solution
import sys
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def build(a):
"""Level order with -1 for a missing child."""
if not a or a[0] == -1:
return None
root = Node(a[0])
q = deque([root])
i = 1
while q and i < len(a):
cur = q.popleft()
if i < len(a) and a[i] != -1:
cur.left = Node(a[i])
q.append(cur.left)
i += 1
if i < len(a) and a[i] != -1:
cur.right = Node(a[i])
q.append(cur.right)
i += 1
return root
def serialize(root):
out, q = [], deque([root])
while q:
n = q.popleft()
if n is None:
out.append(-1)
continue
out.append(n.val)
q.append(n.left)
q.append(n.right)
while out and out[-1] == -1:
out.pop()
return " ".join(map(str, out))
def delete_node(node, key):
if node is None:
return None
if key < node.val:
node.left = delete_node(node.left, key)
elif key > node.val:
node.right = delete_node(node.right, key)
else:
if node.left is None:
return node.right
if node.right is None:
return node.left
m = node.right
while m.left:
m = m.left
node.val = m.val
node.right = delete_node(node.right, m.val)
return node
sys.setrecursionlimit(10000)
data = list(map(int, sys.stdin.read().split()))
k = data[0]
root = delete_node(build(data[1 : 1 + k]), data[1 + k])
print(serialize(root) if root else "EMPTY")Java solution
import java.io.*;
import java.util.*;
public class Main {
static class Node {
long val;
Node left, right;
Node(long v) { val = v; }
}
// level order with -1 for a missing child
static Node build(long[] a) {
if (a.length == 0 || a[0] == -1) return null;
Node root = new Node(a[0]);
ArrayDeque<Node> q = new ArrayDeque<>();
q.add(root);
int i = 1;
while (!q.isEmpty() && i < a.length) {
Node cur = q.poll();
if (i < a.length && a[i] != -1) q.add(cur.left = new Node(a[i]));
i++;
if (i < a.length && a[i] != -1) q.add(cur.right = new Node(a[i]));
i++;
}
return root;
}
static StreamTokenizer in = new StreamTokenizer(new BufferedReader(new InputStreamReader(System.in)));
static long next() throws IOException {
in.nextToken();
return (long) in.nval;
}
static long[] readTree() throws IOException {
int k = (int) next();
long[] a = new long[k];
for (int i = 0; i < k; i++) a[i] = next();
return a;
}
static String serialize(Node root) {
ArrayList<Long> out = new ArrayList<>();
ArrayDeque<Node> q = new ArrayDeque<>();
ArrayList<Node> order = new ArrayList<>();
order.add(root);
for (int h = 0; h < order.size(); h++) {
Node n = order.get(h);
if (n == null) {
out.add(-1L);
continue;
}
out.add(n.val);
order.add(n.left);
order.add(n.right);
}
while (!out.isEmpty() && out.get(out.size() - 1) == -1) out.remove(out.size() - 1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < out.size(); i++) sb.append(i > 0 ? " " : "").append(out.get(i));
return sb.toString();
}
static Node deleteNode(Node n, long key) {
if (n == null) return null;
if (key < n.val) n.left = deleteNode(n.left, key);
else if (key > n.val) n.right = deleteNode(n.right, key);
else {
if (n.left == null) return n.right;
if (n.right == null) return n.left;
Node m = n.right;
while (m.left != null) m = m.left;
n.val = m.val;
n.right = deleteNode(n.right, m.val);
}
return n;
}
public static void main(String[] args) throws IOException {
Node root = build(readTree());
long key = next();
root = deleteNode(root, key);
System.out.println(root == null ? "EMPTY" : serialize(root));
}
}Solve Delete a Node from a BST online · All practice problems