HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Binary Search tree deletion optimization

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
searchoptimizationbinarydeletiontree

Problem

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.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 = m

Solution

You are always returning true so I guess you don't really need current return value. In that case you might want to try a bit different approach.
You want to do something like:

if( data  node.key) {
    node.right = deleteNode(data, node.right);
 } else {
    //here return resulting node after deletion, null if node had no children
 }


That way you don't need to know anything about parent

Code Snippets

if( data < node.key) {
    node.left = deleteNode(data, node.left);
 } else if( data > node.key) {
    node.right = deleteNode(data, node.right);
 } else {
    //here return resulting node after deletion, null if node had no children
 }

Context

StackExchange Code Review Q#111527, answer score: 2

Revisions (0)

No revisions yet.