Example: Delete in BST - rFronteddu/general_wiki GitHub Wiki

public TreeNode deleteNode(TreeNode root, int key) {
        if (root == null) {
            return null;
        }
        
        // If the key is less than the root's value, delete from the left subtree
        if (key < root.val) {
            root.left = deleteNode(root.left, key);
        }
        // If the key is greater than the root's value, delete from the right subtree
        else if (key > root.val) {
            root.right = deleteNode(root.right, key);
        }
        // If the key is equal to the root's value, it's the node to be deleted
        else {
            // Case 1: Node has no children or only one child
            if (root.left == null) {
                return root.right;
            } else if (root.right == null) {
                return root.left;
            }
            
            // Case 2: Node has two children
            // Find the inorder successor (smallest node in the right subtree)
            TreeNode successor = findSuccessor(root.right);
            // Replace the root's value with the successor's value
            root.val = successor.val;
            // Recursively delete the successor node
            root.right = deleteNode(root.right, successor.val);
        }
        
        return root;
    }
    
    // Helper method to find the inorder successor
    private TreeNode findSuccessor(TreeNode node) {
        while (node.left != null) {
            node = node.left;
        }
        return node;
    }