Kay
Kay

Reputation: 845

Why is false being returned in this function

In my program below, I set the variable th as true in the second if statement. I'm curious why it later returns as false.

public boolean nodeExist(TreeNode Tree, T value){

    boolean th = false;

    if(Tree.getValue()!= null){

        if(value == Tree.getValue()){

            th = true;

        }else{

            if(value.compareTo((T) Tree.getValue()) < 0){

                nodeExist(Tree.getLeft(), value);

            }else{

                nodeExist(Tree.getRight(), value);
            }

        }

    }else{

        th = false;

    }

    return th;

}

Upvotes: 0

Views: 163

Answers (3)

polygenelubricants
polygenelubricants

Reputation: 383676

You already got your answer. In future, to prevent mistakes like this, it's better to just return the value right away if you can. IT'S OKAY to have multiple return; if used properly, it can read to more readable code.

public boolean nodeExist(TreeNode Tree, T value){
    if (Tree.getValue() == null) return false;

    if (value == Tree.getValue()) return true;

    if (value.compareTo((T) Tree.getValue()) < 0) {
       return nodeExist(Tree.getLeft(), value);
    } else {
       return nodeExist(Tree.getRight(), value);
    }
}

See also


Additionally, I noticed that you used == instead of equals for object comparison (i.e. T can't be a primitive type). This is rarely correct; equals is almost always what is really intended.

See also


One more style advice, please follow naming convention for Java, where variable names start with lowercase letter, with upper case letter for internal words (so, somethingLikeThis).

Programming isn't about getting things right, it's also about getting things readable. Learn and adopt a good coding style, and follow established conventions.

Upvotes: 1

BradBrening
BradBrening

Reputation: 5518

In the section in which you're doing your compareTo where the th value is not set. If this conditional is met, th can never be set to true.

Upvotes: 0

Johannes Schaub - litb
Johannes Schaub - litb

Reputation: 506837

You probably look at a recursive call which sets th to true. But when that call returns to its caller, that th is still at false, and that's then returned. You need to assign the recursive callee's result:

        if(value.compareTo((T) Tree.getValue()) < 0){

            th = nodeExist(Tree.getLeft(), value);

        }else{

            th = nodeExist(Tree.getRight(), value);
        }

Upvotes: 5

Related Questions