递归函数中的stackoverflow错误

时间:2019-02-23 02:58:56

标签: java binary-search-tree stack-overflow

我在类中有以下函数,将一组数字实现为二叉搜索树。该函数检查输入的整数是否在树中。

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

如果我使用该函数检查树的第一个元素以外的其他内容,则会在线程“主” 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;
             }
         }
     }

1 个答案:

答案 0 :(得分:2)

您有一些问题。您只需要将参数与root.element进行比较。另外,v应该是用户想要搜索的int,并且您传入树的不同元素,而不是用户正在搜索的值:

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

您也忽略了递归调用的结果。您需要重新考虑一下自己的逻辑。您想要将Nodeint(搜索值)传递给方法。您可以为此使用一个重载方法:

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