0

I have a program where I need to search for a specific word in a binary tree, the code I came up with for the search method for the string is not working. if someone could take a look at it I would greatly appreciate it.

I have tried a few alterations to this but it still did not work.

public boolean check(BSTNode t,String key){
    if(!t.word.equals(key)){
        check(t.left,key);
        check(t.right,key);
    }
    else{
        return true;
    }
    return false;
}
1
  • I have edited your tags. Please make sure to choose tags that match the problem, not just words that appear in your question. For example, the binary tag has nothing to do with binary trees. This helps get your question in front of people who can answer it. I also added the java tag, since I believe you are working in Java. Now Stack Overflow can syntax highlight your code correctly. If this is the wrong language please change it. Commented Dec 6, 2016 at 13:33

1 Answer 1

2

This could be written like this;

public boolean check(BSTNode t,String key) {
    return 
      t.word.equals(key) || check(t.left,key) || check(t.right,key)
}

or, more verbosely;

public boolean check(BSTNode t,String key) {
    if (t.word.equals(key)) return true;

    if (check(t.left,key)) return true;

    if (check(t.right,key)) return true;

    return false;
}

You don't need a lot of else statements because the return statements stop execution in the function.

Edit:

You must also check to see that your BSTNode is not null, or you will get null pointer exceptions when you reach the end of the tree. This could be done at the start of the function, or before the inner recursive check calls:

public boolean check(BSTNode t,String key) {

    if (t == null) return false;

    if (t.word.equals(key)) return true;

    if (check(t.left,key)) return true;

    if (check(t.right,key)) return true;

    return false;
}

or;

public boolean check(BSTNode t,String key) {
    if (t.word.equals(key)) return true;

    if (t.left != null && check(t.left,key)) return true;

    if (t.right != null && check(t.right,key)) return true;

    return false;
}
Sign up to request clarification or add additional context in comments.

2 Comments

thank you so much for taking your time to look at my code, i really appreciate it.
You bet. Let me know if you have any questions.

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.