DAA: Insert a node in Binary Search Tree

Insert a node in Binary Search Tree (BST)

We have a Binary search tree and a key. Insert the key in the binary search tree if not present.

In the above figure, the key to be inserted is 5. We have inserted it in the tree, and the modified tree is shown with the blue circle containing 5.

To be more clearer, let us look at another example:

         100                               100

        /   \        Insert 40            /    \

      20     500    --------->          20     500

     /  \                              /  \ 

    10   30                           10   30

                                              \  

                                              40

Approach 1: Recursive

Start the search from the root. If the key to be inserted is less than the root, it will be inserted in the left subtree else right subtree. Follow up until we hit the leaf node, and if there is a vacancy, we put the key at that level.

C++ code:

 #include <iostream>
 using namespace std;
 class BST // Create the BST Tree Structure
     {
     int data; //  node value of BST
     BST *left, *right; // left and right pointers to BST
 public:
     BST(); // Default constructor
     BST(int); // constructor when passed a value
     BST* Insert(BST*, int); // insert a value(key) in the BST
     void Inorder(BST*); // print Inorder traversal of BST
 };
 BST::BST() // Define Default Constructor
     : data(0),
       left(NULL),
       right(NULL)
 {
 }
 BST::BST(int value) // define paramertised Constructor
 {
     data = value;
     left = right = NULL;
 }
 BST* BST::Insert(BST* root, int value) // function to insert the given key
 {
     if (!root) {
         return new BST(value); // if the tree is empty, then the passed key is only the root node
     }
     if (value > root->data) {
         root->right = Insert(root->right, value);
     }
     else {
         root->left = Insert(root->left, value);
     }
     // Return 'root' node, after insertion.
     return root;
 }
 void BST::Inorder(BST* root) // The Inorder traversal
 {
     if (!root) {
         return;
     }
     Inorder(root->left); // in order rule - root--->left
     cout << root->data << endl; // key of root
     Inorder(root->right); // right of root
 }
 int main() // main function
 {
     BST b, *root = NULL;
     root = b.Insert(root, 50);
     b.Insert(root, 30);
     b.Insert(root, 20);
     b.Insert(root, 40);
     b.Insert(root, 70);
     b.Insert(root, 60);
     b.Insert(root, 80);
     b.Inorder(root);
     return 0;
 } 

C code:

 #include <stdio.h>
 #include <stdlib.h>
 struct node { // create BST Tree structure
           int key; // Value of BST Node
           struct node *left, *right; // Left and right pointers to BST Node
 };
 struct node* newNode(int item) // Insert value in the tree
 {
           struct node* temp = (struct node*)malloc(sizeof(struct node)); // Allocate memory
           temp->key = item; // Store the value
           temp->left = temp->right = NULL; // LEft and right point to NULL
           return temp;
 }
 void inorder(struct node* root) // This function will print in order of the tree
 {
           if (root != NULL) {
                    inorder(root->left); // in order rule - root--->left
                    printf("%d \n", root->key); // key of root
                    inorder(root->right); // right of root
           }
 }
 struct node* insert(struct node* node, int key) // The function to insert the key in BST
 {
           if (node == NULL) // If tree is not created yet
                    return newNode(key); // create the key as root
           if (key < node->key) // If key is less than node's value
                    node->left = insert(node->left, key); // it will fit in the left subtree
           else if (key > node->key)
                    node->right = insert(node->right, key); // other wise right subtree
           return node; // return the node
 }
 int main() // main function
 {
           struct node* root = NULL;
           root = insert(root, 50); // the root node
           insert(root, 30);
           insert(root, 20);
           insert(root, 40);
           insert(root, 70);
           insert(root, 60);
           insert(root, 80);
                    inorder(root); // print inorder of the tree created after insertion
           return 0;
 } 

Output

 20
 30
 40
 50
 60
 70
 80 

Time complexity: O(Height of the tree)


Related Topics

Boyer Moore Algorithm

Boyer Moore Algorithm The Boyer Moore algorithm is a searching algorithm in which a string of length n and a pattern of length m is searched. It prints all the occurrences...

11 minutes read.

DAA: Rabin Karp Algorithm

Rabin Karp Algorithm The Rabin Karp or Karp Rabin algorithm is used to matching a specific pattern in the string. It uses the technique of hashing to match a specific text. There also...

6 minutes read.

DAA: Floyd Cycle Detection

Floyd Cycle Detection Floyd Cycle algorithm is one of the cycle detection algorithms to detect the cycle in a given singly linked list. In the Floyd Cycle algorithm, we have two pointers...

4 minutes read.

DAA: Construct a Tree from Inorder and Preorder Traversals

Construct a Tree from Inorder and Preorder Traversals We are given inorder and preorder traversals of a tree. We need to generate a tree from these traversals. Example: Inorder[]   = { 3, 1,...

4 minutes read.

DAA: Euclid Algorithm

Euclid Algorithm The Euclid algorithm finds the GCD of two numbers in the efficient time complexity. To find the GCD of two numbers, we take the two numbers’ common factors and multiply...

8 minutes read.

DAA: Bead Sort Algorithm

Bead Sort Algorithm The bead sort is also known as the gravity sort algorithm. The algorithm is based on the natural phenomena of gravity. The phenomenon is the falling of things...

3 minutes read.

DAA: Density of a Binary Tree Algorithm

The Density of a Binary Tree Algorithm The density of a binary tree is defined as the ratio of the tree’s size to the tree’s height.  The height of the tree is...

2 minutes read.

DAA: Binary Tree and its Categories

Binary Tree and its Categories The binary tree is a non-linear data structure in which there are 0 or utmost 2 nodes.  Each node has two children, i.e., left and right...

4 minutes read.

DAA: Application of DFS and BFS

Application of DFS and BFS Depth-first search and breadth-first searches are the most famous algorithms used in daily life and the programming world. Let us now explore each application in which...

3 minutes read.

DAA: Algorithm to Find the Maximum Width of a Tree

Algorithm to Find the Maximum Width of a Tree The width of a binary tree is defined as the maximum number of nodes at a given level. The level having the...

5 minutes read.

DAA: KMP Algorithm

KMP ALGORITHM The KMP algorithm is abbreviated as the "Knuth Morris Pratt” algorithm. This algorithm was developed by all of them.  This algorithm searches a pattern of length m in a string...

10 minutes read.

DAA: Continuous Tree

Continuous Tree A continuous tree is the one in which the nodes from root to leaf path, the two adjacent node values, have a difference of 1. Input :          3                     /   \                   ...

5 minutes read.

DAA: Dijkstra’s Algorithm (Shortest Path)

Dijkstra’s Algorithm (Shortest Path) Dijkstra’s algorithm finds the shortest distance from a source to all the vertices in a graph. This algorithm is used in network protocols like IS-IS and OSPF(Open...

3 minutes read.

Segregate the given Linked List in DAA

Segregate Even and Odd Nodes in a Linked List A linked list is a linear data structure in which each node has two blocks. One contains the node’s value or data,...

3 minutes read.

DAA: Insertion Sort Algorithm on Singly Link List

Insertion Sort Algorithm on Singly Link List We will sort a singly link list using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The insertion sort technique works...

3 minutes read.

DAA: Algorithm of Right View of a Binary Tree

Algorithm of Right View of a Binary Tree The right view of a binary tree is the visible nodes from the right side of the tree. In the given tree, the visible...

5 minutes read.

DAA: Bottom view of a Binary Tree

Bottom view of a Binary Tree The bottom view of a binary tree is the number of nodes visible when viewed from the bottom. At every horizontal distance, there would be...

3 minutes read.

DAA: Bubble Sort Algorithm on Linked List

Bubble Sort Algorithm on Linked List In this article, we will sort a Link List using the bubble sort technique. Example: Input : 20->30->40->10 Output :10->20->30->40 Input : 20->4->3 Output : 3->4->20 Sorting Technique The bubble sort technique...

4 minutes read.

DAA: Bubble Sort Algorithm

Bubble Sort Algorithm The bubble sort algorithm is also known as the sinking algorithm. In this algorithm, we iterate over the array, and it takes two adjacent elements and swaps them...

3 minutes read.

DAA: Find the Height or Maximum Depth of a Binary Tree

Find the Height or Maximum Depth of a Binary Tree We have a binary tree structure and we need to find its height. It is defined by the distance from the...

3 minutes read.