KatInterview

450. Delete Node in a BST

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The core of this problem is to remove a node from a Binary Search Tree (BST) given its key. The main challenge lies in handling the deletion in a way that preserves the BST properties. Specifically, for any node n, all values in its left subtree must be less than n.val, and all values in its right subtree must be greater than n.val. The operation can be broken down into two parts: finding the node and then restructuring the tree after its removal.

Solution

Delete Node in a BST in Python

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def deleteNode(self, root: Optional[TreeNode], key: int) -> Optional[TreeNode]:
        # Base case: if the tree is empty, return None.
        if not root:
            return None

        # Recursive search for the node to delete.
        if key < root.val:
            # The key to be deleted is in the left subtree.
            root.left = self.deleteNode(root.left, key)
        elif key > root.val:
            # The key to be deleted is in the right subtree.
            root.right = self.deleteNode(root.right, key)
        else:
            # This is the node to be deleted.

            # Case 1 & 2: Node with only one child or no child.
            if not root.left:
                # If no left child, promote the right child.
                return root.right
            elif not root.right:
                # If no right child, promote the left child.
                return root.left
            
            # Case 3: Node with two children.
            # Find the in-order successor (smallest in the right subtree).
            successor = root.right
            while successor.left:
                successor = successor.left
            
            # Copy the successor's value to this node.
            root.val = successor.val
            
            # Delete the in-order successor from the right subtree.
            root.right = self.deleteNode(root.right, successor.val)
            
        # Return the (possibly updated) root of the subtree.
        return root

Delete Node in a BST in Java

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
    public TreeNode deleteNode(TreeNode root, int key) {
        // Base case: if the tree is empty, return null.
        if (root == null) {
            return null;
        }

        // Recursive search for the node to delete.
        if (key < root.val) {
            // The key to be deleted is in the left subtree.
            root.left = deleteNode(root.left, key);
        } else if (key > root.val) {
            // The key to be deleted is in the right subtree.
            root.right = deleteNode(root.right, key);
        } else {
            // This is the node to be deleted.

            // Case 1 & 2: Node with only one child or no child.
            if (root.left == null) {
                // If no left child, promote the right child.
                return root.right;
            } else if (root.right == null) {
                // If no right child, promote the left child.
                return root.left;
            }

            // Case 3: Node with two children.
            // Find the in-order successor (smallest in the right subtree).
            TreeNode successor = root.right;
            while (successor.left != null) {
                successor = successor.left;
            }

            // Copy the successor's value to this node.
            root.val = successor.val;

            // Delete the in-order successor from the right subtree.
            root.right = deleteNode(root.right, successor.val);
        }
        
        // Return the (possibly updated) root of the subtree.
        return root;
    }
}

Delete Node in a BST in C++

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* deleteNode(TreeNode* root, int key) {
        // Base case: If the tree is empty, return null.
        if (!root) {
            return nullptr;
        }

        // Recursive search for the node to delete.
        if (key < root->val) {
            // The key to be deleted is in the left subtree.
            root->left = deleteNode(root->left, key);
        } else if (key > root->val) {
            // The key to be deleted is in the right subtree.
            root->right = deleteNode(root->right, key);
        } else {
            // This is the node to be deleted.

            // Case 1 & 2: Node with only one child or no child.
            if (!root->left) {
                // If no left child, promote the right child.
                TreeNode* temp = root->right;
                // In C++, we might want to free memory, but LeetCode manages it.
                // delete root;
                return temp;
            } else if (!root->right) {
                // If no right child, promote the left child.
                TreeNode* temp = root->left;
                // delete root;
                return temp;
            }

            // Case 3: Node with two children.
            // Find the in-order successor (smallest in the right subtree).
            TreeNode* successor = root->right;
            while (successor && successor->left) {
                successor = successor->left;
            }
            
            // Copy the successor's value to this node.
            root->val = successor->val;
            
            // Delete the in-order successor from the right subtree.
            root->right = deleteNode(root->right, successor->val);
        }
        
        // Return the (possibly updated) root of the subtree.
        return root;
    }
};

Delete Node in a BST in TypeScript

/**
 * Definition for a binary tree node.
 * class TreeNode {
 *     val: number
 *     left: TreeNode | null
 *     right: TreeNode | null
 *     constructor(val?: number, left?: TreeNode | null, right?: TreeNode | null) {
 *         this.val = (val===undefined ? 0 : val)
 *         this.left = (left===undefined ? null : left)
 *         this.right = (right===undefined ? null : right)
 *     }
 * }
 */

function deleteNode(root: TreeNode | null, key: number): TreeNode | null {
    // Base case: if the tree is empty, return null.
    if (!root) {
        return null;
    }

    // Recursive search for the node to delete.
    if (key < root.val) {
        // The key to be deleted is in the left subtree.
        root.left = deleteNode(root.left, key);
    } else if (key > root.val) {
        // The key to be deleted is in the right subtree.
        root.right = deleteNode(root.right, key);
    } else {
        // This is the node to be deleted.

        // Case 1 & 2: Node with only one child or no child.
        if (!root.left) {
            // If no left child, promote the right child.
            return root.right;
        } else if (!root.right) {
            // If no right child, promote the left child.
            return root.left;
        }

        // Case 3: Node with two children.
        // Find the in-order successor (smallest in the right subtree).
        let successor = root.right;
        while (successor.left) {
            successor = successor.left;
        }

        // Copy the successor's value to this node.
        root.val = successor.val;

        // Delete the in-order successor from the right subtree.
        root.right = deleteNode(root.right, successor.val);
    }

    // Return the (possibly updated) root of the subtree.
    return root;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.