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

Insert element in a binary tree. Simple Java example.

Boris~November 20, 2020 /Binary Tree

How to insert an element in a binary tree in Java? That is one of the common questions in any technical interview. The basic logic here is to put elements that value less than the root on the binary tree’s left side. And put the elements that value more than the root element on the right side of the tree. To make it happen, we should write a function based on the recursion.

A critical thing you should keep in mind.

While we are running the recursion, we have to remember about the call stack. You should know how the program is operating the code during recursion.

Code example of how to add an element in a binary tree? The complete solution in Java.

If you implemented the binary tree and want to add the element, you should follow the next steps: 

           if (node == null){
                node = new TreeNode(value);
                return node;
            }
                if (value < node.data){
                node.left = insert(node.left, value);
              } else {
                node.right = insert(node.right, value);
              }

As a result, that function will run itself until it will find the empty (null) space to create a new node and put it there. In this article you figured out, how to insert an element in a binary tree (Java).

Animated:

insert element in binary tree java

Step-by-step schema:

add element in the binary tree
search tree insert element
binary tree adding element

Full code:

private TreeNode insert(TreeNode node, int value){
//Here we creating a new node
            if (node == null){
                node = new TreeNode(value);
                return node;
            }
//Going to the left side of the current node
            if (value < node.data){
                node.left = insert(node.left, value);
            } else {
//Going to the right side of the current node
                node.right = insert(node.right, value);
            }
            return node;
        }

Full code and more examples in my facebook group.

Useful links:

Leave Any Questions Related To This Article Below!