Search an element in a binary tree. Simple Java example. – IT Blog
IT Blog
Boris IT Expert

Search an element in a binary tree. Simple Java example.

Boris~November 20, 2020 /Binary Tree

How to search an element in a binary tree in Java? This problem is one of the fundamental issues in any technical interview. Here, the basic logic is almost the same as inserting the element in the binary tree. To find an element that value less than the root value, we are going on the binary tree’s left side. Suppose the value is more than the root element we are going on the tree’s right side. To make it happen, we should write a function based on the recursion. We are repeating this logic until we find the right node or the last checked node will be null.

A critical thing you should keep in mind.

While we are going through the recursion, we have to keep in mind the call stack. It would help if you understood how the program is running the code during recursion.

An example of how to search for an element in a binary tree? The detailed solution in Java.

If you implemented the binary tree in a sorted way and want to find the element, you should follow the next steps: 

            if (node == null){
                return false;
            }
            if (node.data == value){
                return true;
            }
search element binary tree java
                if (value < node.data){
                return searchRecursive(node.left, value);
            } else {
                return searchRecursive(node.right, value);
            }

As a result, that function will run itself until it will find the needed value or will stop by the null node reference.

Animated:

binary tree search java
src: gfycat.com

Step-by-step schema:

Full code:

private boolean searchRecursive(TreeNode node, int value){
            //If null - means there is no such value in a tree
            if (node == null){
                return false;
            }

            //If data is equals - means we have found needed value
            if (node.data == value){
                return true;
            }

            //Moving on the left side of the tree
            if (value < node.data){
                return searchRecursive(node.left, value);
            } else {
                //Moving on the right side of the tree
                return searchRecursive(node.right, value);
            }
        }

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!