簡體   English   中英

調用另一個類時遞歸不起作用

[英]Recursion not working when called into another class

我編寫了一個遞歸方法,該方法搜索BST ,將參數與節點中的string屬性進行比較,如果字符串匹配,則從該節點返回int屬性。 該方法在其自己的類中調用時有效,但是,當我在另一個類中調用該方法時,該方法不再起作用。 因此,基本上,該方法的private部分有效,而只是public部分使我感到困惑。

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;
}

因此,基本上, private部分是有效的,但是,當我使用public在另一個類中調用遞歸時,它總是返回-1

在另一堂課中,我正在這樣做:

public static void main(String[] args) {

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

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

我省略了實際的Node制作和插入操作,因為我認為這無關緊要。

您的搜索將始終返回-1因為您沒有正確實現搜索。 我不知道為什么在“它自己的類”中運行它時它會起作用,但是您需要返回遞歸調用的值。 否則,遞歸完成后,您將只返回-1

您可以對此進行調整,然后使其生效:

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;
}

這似乎不像在二叉搜索樹中搜索(或BST意味着什么?),它更像是對任意二叉樹的有序遍歷。

您可以使其工作,只是不要忽略遞歸中的返回值:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM