简体   繁体   中英

stackoverflow error in recursive function

I have the following function is in class implementing a set of numbers as a binary search tree.The function checks if the input integer is in the tree.

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

I am getting Exception in thread "main" java.lang.StackOverflowError if I check anything other than the first element of the tree with the function.

Edit: My tree is setup as follows:

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

You have a few problems. You are only every comparing the parameter with root.element . Also, v is supposed to be the int that the user wants to search for, and you pass in the different elements of the tree, not the value that the user is searching for:

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

Also you are ignoring the result of your recursive calls. You need to rethink your logic a little. You want to be passing a Node and an int (the search value) to the method. You can have an overloaded method for this:

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

And then have:

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

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