/* A recursive function to delete an existing key in BST */ Node deleteNode(Node root, int key) { /* Base Case: If the tree is empty */ if (root == null) return root;
/* Otherwise, recur down the tree */ if (key < root.key) root.left = deleteNode(root.left, key); elseif (key > root.key) root.right = deleteNode(root.right, key);
// if key is same as root's // key, then This is the // node to be deleted else { // node with only one child or no child if (root.left == null) return root.right; elseif (root.right == null) return root.left;
// node with two children: Get the inorder // successor (smallest in the right subtree) root.key = minValue(root.right);
// Delete the inorder successor root.right = deleteNode(root.right, root.key); }