Search code examples
javasearchiterationbinary-search-tree

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

Solution

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