Binary Search tree (Insertion)

   A tree in which every node can have a maximum of two children is called a binary tree.
      A binary search tree is a binary tree in which every node has lower values in the left sub tree and higher values in the right sub tree.

Node of binary tree:

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

BST - Insertion:

 static Node Insert(Node root,int data) {
     if( root == null ){
           root = new Node(data);
           return root;
     }
     if( data < root.data)
            root.left = Insert(root.left,data);
     else
            root.right = Insert(root.right,data);
      
     return root;  

 }

Explanation:

  If the root is null we insert the node there itself. If data is less than root we recursively call the function with left node. Else we recursively insert it in right sub tree. After insertion return the root node.

Illustration:

Insert 3




     


       

Comments

Popular posts from this blog

Tree traversals - Inorder Traversal

Stack implementation using array