Delete a node from BST Hackerrank solution JAVA
Explanation:
/* class Node
{
int key;
Node left, right;
Node(int item)
{
key = item;
left = right = null;
}
}*/
class GfG
{
Node deleteNode(Node root, int key)
{
/* If the tree is empty */
if (root == null) return root;
if (key < root.key)
root.left = deleteNode(root.left, key);
else if (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;
else if (root.right == null)
return root.left;
// node with two children: Get smallest in the right subtree
root.key = minValue(root.right);
// Delete the inorder successor
root.right = deleteNode(root.right, root.key);
}
return root;
}
static int minValue(Node root)
{
int minv = root.key;
while (root.left != null)
{
minv = root.left.key;
root = root.left;
}
return minv;
}
}
0 Comments:
Post a Comment