Austin Lee
Austin Lee

Reputation: 1

Find function recursively Binary Tree

I have a bit of problem doing this function: public boolean find(Integer i)

At first I tried:

public boolean find(Integer i) {
    Node currNode = root;

    if (currNode.getData() != i) {
        return false; // we didnt find it
    }
    if (currNode.getLeft() != null && find(currNode.getLeft().getData())) {
        return true;
    }
    if (currNode.getRight() != null && find(currNode.getRight().getData())) {
        return true;
    }
    else 
        return false;
}

But this is only giving me false in my test case. I was wondering how to find a specific data in the binary tree and return true if the input data is found within the binary tree.

Upvotes: 0

Views: 43

Answers (1)

cdlane
cdlane

Reputation: 41872

Based on the code you provided, I'm guessing this is more like what you want:

public boolean find(Integer i) {

    if (getData().intValue() == i.intValue()) {
        return true; // we found it
    }

    if (getLeft() != null && getLeft().find(i)) {
        return true;
    }

    if (getRight() != null && getRight().find(i)) {
        return true;
    }

    return false;
}

If not, provide more of your solution code to help guide a better answer.

Upvotes: 1

Related Questions