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

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.

DAA: Depth-First Search Algorithm

Depth-first search: DFS is a traversing algorithm of a graph or tree in which one node is taken as arbitrary, and with the help of that arbitrary node, all its...

6 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.

Symmetric Trees in DAA

Symmetric Trees The trees that are mirror images of themselves are known as symmetric trees. Look at the following tree image below: The tree is symmetric as the left subtree is the mirror...

4 minutes read.

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,...

4 minutes read.

Introduction to Sorting in DAA

DAA: What is Sorting? The technique in which a data structure is rearranged in decreasing order, increasing order, or in a specified order is called sorting. We apply to sort in our...

4 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: 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: 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: 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: 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.

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: 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: 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.

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: Dynamic Programming

Dynamic Programming Introduction The technique of breaking a problem statement into subproblems and using the optimal result of subproblems as an optimal result of the problem statement is known as dynamic programming....

2 minutes read.

DAA: Breadth First Search (BFS) for a Graph

Breadth First Search (Bfs) For A Graph The algorithm in which all the graph nodes are traversed is known as the breadth-first search algorithm. In this algorithm, we select one node,...

5 minutes read.

Recurrence relation in DAA

Recurrence relation in DAA The model that uses mathematical concepts to calculate the time complexity of an algorithm is known as the recurrence relational model. A recursive relation, T(n), is a recursive...

5 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: 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.