简体   繁体   中英

Recursion not working when called into another class

I wrote a recursive method which searches through a BST , compares the argument with the string property in the node, and returns the int property from that node if the strings match. The method works when it's called in it's own class, however, when I call it into a different class, it doesn't work anymore. So basically, the private part of the method works, its just the public part that's messing me up.

public int boka(String ime) {
    int bobo=boka(this.root,ime);
    return bobo;
}

private int boka(Node curr_root,String ime){
    if(curr_root==null){
        return -1;
    }

    boka(curr_root.left,ime);
    if(curr_root.info.ime.equalsIgnoreCase(ime)) {
        return curr_root.info.pobjede;
    }
    boka(curr_root.right,ime);
    return -1;
}

So basically, the private part works, however, when I call the recursion in another class using the public , it always returns -1 .

In the other class, I'm doing this:

public static void main(String[] args) {

    // TODO Auto-generated method stub
    BinTree bt = new BinTree();

    int a = bt.boka("Djole");

I omitted the actual Node making and inserting, since I don't think that's relevant.

Your search will always return -1 because you haven't properly implemented the search. I don't know why it's working when you run it in "it's own class" but you need to return the value of the recursive call; otherwise, you are just returning -1 when the recursion is complete.

You can adjust your algorithm to this, and get it to work:

private int boka(Node curr_root,String ime){

    if(curr_root.left != null) return boka(curr_root.left,ime);

    if(curr_root.info.ime.equalsIgnoreCase(ime)) return curr_root.info.pobjede;

    if(curr_root.right != null) return boka(curr_root.right,ime);

    return -1;
}

That does not seem like searching in a Binary Search Tree (or what else BST means?), it is more like an in-order traverse of an arbitrary binary tree.

You can make it working, just do not disregard the return values in the recursion:

private int boka(Node curr_root,String ime){
  if(curr_root==null) {
    return -1;
  }

  int ret=boka(curr_root.left,ime);
  if(ret!=-1) {
    return ret
  }

  if(curr_root.info.ime.equalsIgnoreCase(ime)) {
    return curr_root.info.pobjede;
  }

  return boka(curr_root.right,ime);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM