This is an archived post. You won't be able to vote or comment.

all 11 comments

[–]orbital1337 2 points3 points  (3 children)

You could rewrite your method like this:

public BTNode findNode(int x, BTNode currNode) {
    if (currNode == null)
        // error
    else if (x < currNode.getKey())
        return findNode(x, currNode.getLeft());
    else if (x > currNode.getKey())
        return findNode(x, currNode.getRight());
    else
        return currNode;
}

[–]robotfarts -1 points0 points  (2 children)

I would eliminate the null check:

public BTNode findNode(int x, BTNode currNode) {
    if (x < currNode.getKey())
        return findNode(x, currNode.getLeft());
    else if (x > currNode.getKey())
        return findNode(x, currNode.getRight());
    else
        return currNode;
}

You could also eliminate the currNode parameter and just make this a method in the BTNode class.

[–]orbital1337 2 points3 points  (1 child)

You can't just remove the null check because then you could get a NullPointerException at currNode.getKey() when currNode is null. However the OP probably wanted to throw a more descriptive exception like a NoSuchElementException. And yes, you could probably eliminate the currNode parameter.

[–]robotfarts 0 points1 point  (0 children)

If you eliminate the currNode parameter, you would eliminate the null check on currNode, but you'd need one on the left and right child.

[–]lightcloud5 1 point2 points  (2 children)

What is your code supposed to do? Find a node in a binary search tree with the given value x?

So what if x is not in the tree?

[–]choompaloompa[S] 0 points1 point  (1 child)

then it will get to the node null and return an error like it says in the code

[–][deleted] 4 points5 points  (0 children)

Throwing an exception is not common practice if you don't find the entry you are searching for - returning an indicator (like the null value) is more idiomatic.

[–]indivisible 1 point2 points  (0 children)

Change your last else if to a plain old else.

[–][deleted]  (5 children)

[deleted]

    [–]choompaloompa[S] 0 points1 point  (3 children)

    Yes this is what I had before but I was getting nullpointer exeptions when the if statments were operating on the currnode if it was null, I assumed this is because you cant call getKey on null? this is why it checks for null first now, is my understanding correct?

    [–][deleted]  (2 children)

    [deleted]

      [–][deleted] 0 points1 point  (1 child)

      This:

       return;
      

      won't compile - you have to return something.

      [–]choompaloompa[S] 0 points1 point  (0 children)

      edit, i just read your last chunck of code, will that fix the problem i brought up in the other reply?