I have just started implementing Binary Search tree on my own without using any tutorials online. Please have a look and suggest how can I make code less cluttered and more faster. Right now I am using lots of if-else conditions and want to remove them as much as I can.
boolean deleteNode(int data, TreeNode node )
{
if( data < node.key) deleteNode(data, node.left);
else if( data > node.key) deleteNode(data, node.right);
else {
System.out.println("Value of node = " + node.key);
//case 1 - Left and Right is null - Leaves
if(node.left == null && node.right == null)
{
if(node == node.parent.left)node.parent.left = null;
else node.parent.right = null;
System.out.println("Inside first if");
}
//case 2 - One child is null
else if(node.left !=null && node.right ==null)
{
if(node == node.parent.left)node.parent.left = node.left;
else node.parent.right = node.left;
}
else if(node.right !=null && node.left ==null)
{
if(node == node.parent.right)node.parent.right = node.right;
else node.parent.left = node.right;
}
//case 3 - Delete node is an internal node
else if(node.left !=null && node.right !=null)
{
TreeNode minNode = treeMin(node.right);
if(minNode.parent == node)
{
if(node.parent == null)
{
node.key = minNode.key;
node.right = minNode.right;
}
else{
if(node == node.parent.left)
{
node.parent.left.key = minNode.key;
node.parent.right.right = minNode.right;
}
if(node == node.parent.right)
{
node.parent.right.key = minNode.key;
node.parent.right.right = minNode.right;
}
}
}
else
{
if(node == node.parent.left)
{
node.parent.left.key = minNode.key;
node.left.right = minNode.right;
}
else if(node == node.parent.right)
{
node.parent.right.key = minNode.key;
node.right.left = minNode.right;
}
}
}
}
return true;
}
switch
statements to make it more readable. \$\endgroup\$if
"loop". \$\endgroup\$left.key = minNode.key; node.parent.right.right = minNode.right;
is probably erroneous as well as dispensable: in effect, all three cases withnode->right == minNode
(minNode.parent == node
) are identical: just use the first notation. ((node->right == minNode) == (null == node->right->left)
)null == minNode->left
does not mean that you need to keepminNode
andminNode->right
, only: in theminNode.parent != node
branch, there's at leastnode->right
, which may or may not beminNode.parent
, and possibly quite a lot more, and both handlings look wrong. \$\endgroup\$deleteNode()
looks very similar to AnkitSablok's question re. Dictionary implemented using a Binary Search Tree - is there a text book/other reference it would be of advantage for readers of both questions to know? \$\endgroup\$