Home > Software engineering >  I want to search for values in binary search tree using iteration
I want to search for values in binary search tree using iteration

Time:03-21

Hello I wrote this method to search for values in my binary search tree but it is always returning false whether the value is found in my bst or not. can someone please tell me what's my mistake and how I can fix it.

    public boolean search(int key) {
    BinaryTreeNode subRoot = null;
          
        while (subRoot != null)  
        {  
             
            if (key > subRoot.getData()) {
                root = subRoot.getRight();  
            }
             
            else if (key < subRoot.getData())  
                root = subRoot.getLeft();  
            else
                System.out.println("Searching for "   key   ": found");
                return true; 
        }  
        System.out.println("Searching for "   key   ": NOT found");
        return false;  
    
}

CodePudding user response:

Not having more input this is everything I can do. You forgot to assign subRoot to root at the beginning. You here assigning values to your root in the loop this would lead to loss of data and most likely a infinite-loop. Plus your else statement had no brakets, so it would always return true if you entered the loop.

public boolean search(int key) {
BinaryTreeNode subRoot = root;
      
    while (subRoot != null)  
    {  
         
        if (key > subRoot.getData()) 
            subRoot = subRoot.getRight();             
        else if (key < subRoot.getData())  
            subRoot = subRoot.getLeft();  
        else{
            System.out.println("Searching for "   key   ": found");
            return true;
        } 
    }  
    System.out.println("Searching for "   key   ": NOT found");
    return false;  

}

CodePudding user response:

The problem is that you initialize subRoot with null before the while loop, so when you check the condition it will always be false, therefore going to the end of the function

  • Related