0

I am learning java. I tried to implement basic binary search to understand difference in reference in java and reference/pointers in c++.

The implementations is as following ( using recursion )

 class Node{
    public int value;
    public Node left;
    public Node right; 
    Node( int v ){
        this.value = v;
        this.left = null;
        this.right = null;
    }
}
class binarySearch{
    public Node root;
    public Node insert( int value , Node r ){
        if( r == null ){
            return new Node( value );
        }
        if( r.value < value ){
            r.left = insert( value , r.left);
        }else{
            r.right = insert( value , r.right);
        }
        return r;
    }
    public void insertIt( int v){
        this.root = insert( v , this.root);
    }
    binarySearch(){
        this.root = null;
    }
}

and main

binarySearch b = new binarySearch();
b.insertIt(5 );
b.insertIt(6);
Node p = b.root;
while( p != null ){
    System.out.println("Hi :"  + p.value);
    p = p.right;
}

But the left and right nodes remain null . The recursion does not return the reference to the newly created Node so the value isn't inserted to the left/right nodes of root node.

Why is this happening in java? Is there any special way for recursion and reference or how exactly does the reference works in java?

Thanks for explanations or links and help!

4
  • Possible duplicate of Is Java "pass-by-reference" or "pass-by-value"? Commented Sep 22, 2016 at 19:14
  • 1
    @MouseEvent No. It's a problem with the logic. Commented Sep 22, 2016 at 19:15
  • @trolkura can you include exactly what is output by the above code? How do you know the left/right nodes remain null... your code above only checks the right node; except I would expect it to create a tree with a root node, left branch and a null right branch Commented Sep 22, 2016 at 19:17
  • If you rewrite your code to be one block with a main method it would make it easier for people to help you. Commented Sep 22, 2016 at 19:32

1 Answer 1

2

You swapped your logic. In the insert() function:

if (r.value < value) {
    r.left = insert(value, r.left);
} else {
    r.right = insert(value, r.right);
}

should be:

if (r.value > value) {
// or if (value < r.value) {
    r.left = insert(value, r.left);
} else {
    r.right = insert(value, r.right);
}

As it is now, you're inserting 6 into the left node, so it doesn't show up when you're printing the tree.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.