user2776326
user2776326

Reputation: 65

Binary Tree: Why Does One Insert Method Work and the Other Not

I just learned about binary trees and I tried to create an insert method. My first method did not work and I did a bit of tweaking. It now works but I do not understand why the previous method failed.

The method that does not work is:

if(root == null)
    {
        root = new Node(data);
    }
    else if(data < root.getData())
    {
        insertNode(root.getLeft(), data);
    }
    else
    {
        insertNode(root.getRight(), data);
    }

The method that does work is:

    if(data < root.getData())
    {
         if(root.getLeft() == null)
         {
             root.left = new Node(data);
         }
         else
         {
             insertNode(root.getLeft(), data);
         }
     }

     else
     {
         if(root.getRight() == null)
         {
             root.right = new Node(data);
         }
         else
         {
            insertNode(root.getRight(), data);
         }
     }

Any explanations as to why this is the case? Because the way I see it, root should be equal to root.left, so setting root to a new Node should be the same as setting root.left/right to a new Node.

Upvotes: 1

Views: 117

Answers (2)

aUserHimself
aUserHimself

Reputation: 1597

Assuming that you call the method recursively, insertNode(root, data), you have to be sure that root is not null, which means executing root = new Node(data); creates an object whose visibility is limited to insertNode method.

If not, you can rewrite insertNode(data) to be non-recursive and create the root inside it if it is null.

public void insert(int data) {
    if(root == null){
        root = new Node(data);
    }
    else {
        Node current = root;
        Node previous;
        String from;
        while(current != null) {
            previous = current;
            if(data < current.getData()) {
                current = current.left();
                from = "left";
            }
            else {
                current = current.right();
                from = "right";
            }
        }
        current = new Node(data);
        if(from.equals("left")) {
            previous.left() = current;
        } else {
            previous.right() = current;
        }
    }
}

Upvotes: 0

Manuel Manhart
Manuel Manhart

Reputation: 5455

In your first method, you would give null into your insertNode method, but no reference pointer. Therefore you set root = new Node() in the insertNode method, but the parent node does not know any of this, it still points to null.

Since this is some very basic Java understanding, I recommend reading some articles about "java parameter passing" e.g. http://javadude.com/articles/passbyvalue.htm

Upvotes: 2

Related Questions