bene96
bene96

Reputation: 65

Recursive function return incorrectly returns false

I'm currently coding up a binary search tree and currently trying to implement a recursive function that determines if a node exists within the binary tree.

Here's the node class:

public class BSTNode
{
  public String data; // use this for data and key
  public BSTNode parent, leftchild, rightchild;

  public BSTNode(String key)
  {
      this.data = key;
  }

  public Boolean Exists(String search)
  {
    if(data.equals(search))
        return true;
    else
    {
        if (search.compareToIgnoreCase(data) < 0 && leftchild != null)
        {
            leftchild.Exists(search);
        }
        else if (search.compareToIgnoreCase(data) > 0 && rightchild != null)
        {
            rightchild.Exists(search);
        }       
    }
    return false;
 }



  public void Insert(String key)
  {
    if(key.compareToIgnoreCase(data) < 0)
    {
        if(leftchild == null)
            leftchild = new BSTNode(key);
        else
            leftchild.Insert(key);
    }
    else
    {
        if(rightchild == null)
            rightchild = new BSTNode(key);
        else
            rightchild.Insert(key);
    }
  }

}

The function in question is the Exists function. This is called on the root node of the BST like so: root.Exists("Value");

The base case for the Exists function correctly executes when the node is finally met, however the return false; statement is executed when the return stack is unwinded. I don't seem to be able to alter the function to remove the return false; statement.

Upvotes: 3

Views: 216

Answers (1)

Eran
Eran

Reputation: 394126

You forgot to use the value returned by the recursive calls :

  public Boolean Exists(String search)
  {
    if(data.equals(search))
        return true;
    else
    {
        if (search.compareToIgnoreCase(data) < 0 && leftchild != null)
        {
            return leftchild.Exists(search);
        }
        else if (search.compareToIgnoreCase(data) > 0 && rightchild != null)
        {
            return rightchild.Exists(search);
        }       
    }
    return false;
 }

Upvotes: 4

Related Questions