Searching operation in BST

Viewed 69

Here is my code to search elements is Binary Search Tree using java. When I am executing the search method twice then the output for the second element is showing false. Like 10 is present in the tree then also it's showing false for that element. The code was too long so, I had to remove the Inorder traversal and Insert elements method.

public class BinarySearchTree {
    class Node {
        int data;
        Node left, right;

        public Node(int item) {
            data = item;
            left = right = null;
        }
    }

    Node root;

    BinarySearchTree() {
        root = null;
    }

    // search data method

    boolean search(int data) {
        root = searchData(root, data);
        if (root != null) {
            return true;
        }
        return false;
    }

    Node searchData(Node root, int data) {
        if (root == null) {
            return null;
        }

        if (data == root.data) {
            return root;
        } else if (data < root.data) {
            return searchData(root.left, data);
        } else {
            return searchData(root.right, data);
        }
    }

    
    public static void main(String[] args) {
        BinarySearchTree bst = new BinarySearchTree();
        bst.insert(60);
        bst.insert(30);
        bst.insert(10);
        
        System.out.println("Number found : " + bst.search(60));
        System.out.println("Number found : " + bst.search(10));

    }
}

Console output for the above code: - Number found: true Number found: false

1 Answers

In method search you reassign root value in line

root = searchData(root, data);

To avoid it change this line to

Node root = searchData(this.root, data);

to create new variable, instead of changing object field.
Or change your method to

boolean search(int data) {
    return searchData(root, data) != null;
}
Related