Ad

I Want To Search For Values In Binary Search Tree Using Iteration

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

Answer

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;  

}
Ad
source: stackoverflow.com
Ad