Algo-Sim › Binary Trees & BST

Delete Node in a BST

Medium · Binary Trees & BST · step through it in Java, Python and C++ on your own input

Find the node; a node with at most one child is replaced by that child, a node with two takes its successor’s value instead.

Problem

Delete the node holding key from a binary search tree, if there is one, and return the root of the tree that remains, which must still be a valid BST.

Constraints

Edge cases to test

Follow-up questions

Successor or predecessor?
Either keeps the BST order; alternating can keep the tree more balanced.
What is the cost?
O(h): one walk down to the node and one more to its successor.

Solution

Java

public TreeNode deleteNode(TreeNode root, int key) {
    if (root == null) return null;
    if (key < root.val) root.left = deleteNode(root.left, key);
    else if (key > root.val) root.right = deleteNode(root.right, key);
    else {
        if (root.left == null) return root.right;
        if (root.right == null) return root.left;
        TreeNode succ = root.right;
        while (succ.left != null) succ = succ.left;
        root.val = succ.val;
        root.right = deleteNode(root.right, succ.val);
    }
    return root;
}

Python

def delete_node(root, key):
    if not root:
        return None
    if key < root.val:
        root.left = delete_node(root.left, key)
    elif key > root.val:
        root.right = delete_node(root.right, key)
    else:
        if not root.left:
            return root.right
        if not root.right:
            return root.left
        succ = root.right
        while succ.left:
            succ = succ.left
        root.val = succ.val
        root.right = delete_node(root.right, succ.val)
    return root

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    TreeNode *deleteNode(TreeNode *root, int key) {
        if (root == nullptr)
            return nullptr;
        if (key < root->val)
            root->left = deleteNode(root->left, key);
        else if (key > root->val)
            root->right = deleteNode(root->right, key);
        else {
            if (root->left == nullptr)
                return root->right;
            if (root->right == nullptr)
                return root->left;
            TreeNode *succ = root->right;
            while (succ->left != nullptr)
                succ = succ->left;
            root->val = succ->val;
            root->right = deleteNode(root->right, succ->val);
        }
        return root;
    }
};

More Binary Trees & BST problems