user3048786
user3048786

Reputation: 41

Deleting a node in Binary Tree

Below is the code I wrote for the case when the deleteItem is at the leaf node. Even if I am equating the found leaf node to "null" then also when I print the inorder traversing order if the tree, that element is not deleted and comes on the screen. What am I missing?

public void deleteNode(T deleteItem)
    {
        TreeNode<T> node = root;
        if(root == null)
        {
            System.out.print("Binary Tree does not exist");
            System.exit(0);
        }
        while((node.data != deleteItem) && (node.leftNode != null || node.rightNode != null))
        {
            if(deleteItem.compareTo(node.data)<0)
                node = node.leftNode;
            else
                node = node.rightNode;
        }
        //System.out.printf("deleting item is: %s\n", node.data);
        if(node.data != deleteItem)
        {   
            System.out.println("\ndeleteItem not found in the tree");
            System.exit(0);
        }
        else
        {
            if(node.leftNode == null && node.rightNode == null)
            {
                node = null;
            }
        }
    }

Upvotes: 0

Views: 131

Answers (1)

Kerollos Asaad
Kerollos Asaad

Reputation: 13

Java is "Pass-by-value", so TreeNode<T> tmp = root here means assigning tmp's references to root which means simply you have two different references to the same instance. According to that when you say node = null you set your local references to null which means that the node's parent is still reference to it. So to remove leaf node from the tree you need to keep track of its parent and then removing the reference to the node (removed the reference in the tree not you local copy) which will be something like that:

public void deleteNode(T deleteItem) {
        TreeNode<T> node = root;
        TreeNode<T> parent = null; // parent of the deleted node.
        if(root == null) {
            System.out.print("Binary Tree does not exist");
            System.exit(0);
        }
        while((node.data != deleteItem) && 
              (node.leftNode != null || node.rightNode != null)) {
            parent = node; // keep track of the parent of the deleted node
            if(deleteItem.compareTo(node.data) < 0)
                node = node.leftNode;
            else
                node = node.rightNode;
        }
        if(node.data != deleteItem) {   
            System.out.println("\ndeleteItem not found in the tree");
            System.exit(0);
        }
        else {
            if(parent.leftNode == node)
                parent.leftNode = null;
            else
                parent.rightNode = null;
        }
    }

Upvotes: 1

Related Questions