簡體   English   中英

遞歸函數中的stackoverflow錯誤

[英]stackoverflow error in recursive function

我有以下函數在類中實現一組數字作為二叉搜索樹。該函數檢查輸入整數是否在樹中。

 public boolean isIn(int v){

     if(root != null){  
        if(v == root.element){
            System.out.print(root.element);
            return true;
        }
        isIn(root.left.element);
        isIn(root.right.element);
       }
       return false;
     }

如果我使用函數檢查樹的第一個元素以外的其他內容,則在線程“ main” java.lang.StackOverflowError中得到異常

編輯:我的樹設置如下:

public class BSTSet{
   private TNode root;

   public BSTSet(){
     root = null;
   }



public BSTSet(int[] input){
     int len = input.length;
      for (int i = 0; i<len-1; i++ ) {
           add(input[i]);
      }

   }

   public void add(int v) {
         if (root == null) {
             root = new TNode( v, null,null);
             return;
         }

         TNode node = root;
         while (true) {
             if (v < node.element) {
                 if (node.left == null) {
                     node.left = new TNode( v, null,null);
                     break;
                 }
                 node = node.left;
             } else if(v>node.element){
                 if (node.right == null) {
                     node.right = new TNode(v, null,null);
                     break;
                 }
                 node = node.right;
             }
             else{
               break;
             }
         }
     }

你有幾個問題。 您只需將參數與root.element進行比較。 同樣, v應該是用戶想要搜索的int,並且您傳遞樹的不同元素,而不是用戶正在搜索的值:

isIn(root.left.element);
isIn(root.right.element);

另外,您將忽略遞歸調用的結果。 您需要重新考慮一下自己的邏輯。 您想要將Node和一個int (搜索值)傳遞給該方法。 您可以為此使用一個重載方法:

public boolean isIn(int v){
    return isIn(v, root);
}

然后有:

public boolean isIn(int v, Node node){
    if(node != null){  
        if(v == node.element){
            System.out.print(node.element);
            return true;
        }
        return isIn(v, node.left) || isIn(v, node.right);

    }
    return false;
}

暫無
暫無

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

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