繁体   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