Find a value in a binary tree avoiding stackoverflow exception

Viewed 17382

I'm trying to find a value in a binary tree and returning the node that has the value I'm looking for.

I did an algorithm that works well when the value is not in a very deep level of the tree, but when the value is in a deep position I get a java.lang.StackOverflowError. Here is my code:

class Nope {
    
    Nope left, right;
    int value;

    public Nope find(int v){
        if(v > this.value && this.right != null)
            return right.find(v);
        if(v < this.value && this.left != null)
            return left.find(v);
        if(this.value == v)
            return this;
        return null;
    }
}

Can any one suggest me a solution about this issue (I heard about something like tail optimization recursion) but I'm not sure of it working in Java.

4 Answers
Related