Binary Tree Insertion With Example

In this tutorial we will perform an operation of Insertion of Node in Binary Tree. With some examples we will learn about it.

Insertion a node in Binary Tree
Insertion a node in Binary Tree

Complete Example To Insert A Node in B Tree

In the below example first we created a Tree then printing it using the Preorder Traversal then inserting a node in the existing tree, After that we are again printing it using the Preorder Traversal method. A Recursive process is used to complete this algorithm.


public class BinaryTreeBT {

    static class Node {
        int data;
        Node left;
        Node right;

        Node(int data) {
            this.data = data;
            this.left = null;
            this.right = null;
        }
    }

    // creating binary tree
    static class BinaryTree {
        static int id = -1;

        public static Node createBinary(int nodes[]) {
            id++;
            if (nodes[id] == -1) {
                return null;
            }
            Node myNode = new Node(nodes[id]);
            myNode.left = createBinary(nodes);
            myNode.right = createBinary(nodes);
            return myNode;
        }

        /* function to insert element in binary tree */
        public static Node add(Node current, int value) {
            if(current == null){
                return new Node(value);
            }
            if (value < current.data) {
                current.left = add(current.left, value);
            } else if (value > current.data) {
                current.right = add(current.right, value);
            } else {
                // value already exists
                return current;
            }
        
            return current;
        }

    }

     // preorder traversal
     public static void preOrderTraversal(Node root) {
        if (root == null) {
            return;
        }
        System.out.print(root.data + " ");
        preOrderTraversal(root.left);
        preOrderTraversal(root.right);
    }


    public static void main(String[] args) {
        int nodeArr[] = { 1, 2, 4, -1, -1, 5, -1, -1, 3, -1, 6, -1, -1 };
        BinaryTree tree = new BinaryTree();
        Node result = tree.createBinary(nodeArr);

        System.out.println();
        System.out.println("Old Tree");

        preOrderTraversal(result);

        System.out.println();
        System.out.println("New Tree");

        result = tree.add(result, 12);
        preOrderTraversal(result);
       
    }
}

Answer:
Old Tree
1 2 4 5 3 6

New Tree
1 2 4 5 3 6 12

Thank you for visiting the tutorial. You can comment in the comments section below for any doubts and query. You can also post your content here. See more.

Thank You FlutterTPoint
Thank You FlutterTPoint

Don’t miss new tips!

We don’t spam! Read our [link]privacy policy[/link] for more info.

Leave a Comment

Scroll to Top