P R
P R

Reputation: 1301

Binary Tree in Java

I am trying to code up my own binary tree. Though I could find many examples for a binary search tree, I decided to write this myself.

So far, I've come upto this:

public class bTree {
bnode root=null;

void add(int val){
    bnode newnode= new bnode(val);
    bnode curr = this.root;
    bnode parent = null;

    if(this.root == null){
        this.root = newnode;
        System.out.println("Inserted at root \t"+newnode.value);
    }
    else{
            while( curr != null){
            System.out.println("Current Left and Right\t"+curr.left+"\t"+curr.right);

            if(curr.left == null){
                curr =  curr.left;
                curr = newnode;
                System.out.println("Inserted Left\t" +newnode.value);
                return;
            }
            if(curr.right ==  null){
                curr =  curr.right;
                curr = newnode;
                System.out.println("Inserted Right\t" +newnode.value);
                return;
            }
        }
    }
}

When I try to add the values to the binary tree, only the root is able to add the values. I am slowly trying to write the rest of the code where it finds the left child to be full and backtracks and all the cases. My question is why is it not even adding the next value to the left most child (in the second call to it). I'd really appreciate it if you don't give me the code, I want to learn.

Upvotes: 0

Views: 4712

Answers (3)

doobop
doobop

Reputation: 4520

In your statements here:

        if(curr.left == null){
            curr =  curr.left;
            curr = newnode;
            ...
        }

When you make the assignment "curr = curr.left", "curr" gets assigned null and is no longer referencing anything in the tree. So that the tree will reference it, you'll need assign the left link of "curr" to the new node

        if(curr.left == null){
            curr.left = newnode;
            ...
        }

Here's a picture showing the difference between the two: enter image description here

Upvotes: 3

johnchen902
johnchen902

Reputation: 9609

Why is it not even adding the next value to the left most child in the second call to it?

Because this do not assign curr.left to newnode:

curr = curr.left;
curr = newnode;

Fix:

curr = curr.left = newnode;

Note that there are still other bugs in your code. You'll find them out with more calls.

Upvotes: 2

radai
radai

Reputation: 24202

because when you enter you else {} curr is always != null (because curr=root and root!=null), so the loop never executes

Upvotes: 1

Related Questions