0

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;

}
pandorym
  • 475
  • 4
  • 14
Kay
  • 845
  • 7
  • 21
  • 33

3 Answers3

5

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);
        }
Johannes Schaub - litb
  • 496,577
  • 130
  • 894
  • 1,212
1

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.

Community
  • 1
  • 1
polygenelubricants
  • 376,812
  • 128
  • 561
  • 623
0

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.

BradBrening
  • 5,418
  • 25
  • 30