Like a linked list we can also delete a node from binary search tree. This operation perform O(log(n)) time complexity.
Here is an example of deletion :
private TreeNode delete(TreeNode rootNode, int k)
{
// create a node to store temp data
TreeNode node, node2, n;
if (root.getValue() == k)
{
// create both left and right node
TreeNode leftNode, rightNode;
leftNode = root.getLeftNode();
rightNode = root.getRightNode();
// return null if its last node or leaf
if (leftNode == null && rightNode == null)
return null;
else if (leftNode == null)
{
node = rightNode;
return node;
}
else if (rightNode == null)
{
node = leftNode;
return node;
}
else
{
node2 = rightNode;
node = rightNode;
while (node.getLeftNode() != null)
node = node.getLeftNode();
node.setLeftNode(leftNode);
return node2;
}
}
// traverse to correct node by checking node value, if vallue is greater than //current node then go right otherwise go left.
if (k < root.getValue())
{
n = delete(root.getLeftNode(), k);
root.setLeftNode(n);
}
else
{
n = delete(root.getRightNode(), k);
root.setRightNode(n);
}
return root;
}
0 Comment(s)