Insertion in Binary Search Tree (BST)
Last Updated :
28 Jul, 2023
Given a BST, the task is to insert a new node in this BST.
Example:
Insertion in Binary Search Tree
How to Insert a value in a Binary Search Tree:
A new key is always inserted at the leaf by maintaining the property of the binary search tree. We start searching for a key from the root until we hit a leaf node. Once a leaf node is found, the new node is added as a child of the leaf node. The below steps are followed while we try to insert a node into a binary search tree:
- Check the value to be inserted (say X) with the value of the current node (say val) we are in:
- If X is less than val move to the left subtree.
- Otherwise, move to the right subtree.
- Once the leaf node is reached, insert X to its right or left based on the relation between X and the leaf node’s value.
Follow the below illustration for a better understanding:
Illustration:
Insertion in BST
Insertion in BST
Insertion in BST
Insertion in BST
Insertion in BST
Insertion in Binary Search Tree using Recursion:
Below is the implementation of the insertion operation using recursion.
C++14
#include <bits/stdc++.h>
using namespace std;
class BST {
int data;
BST *left, *right;
public :
BST();
BST( int );
BST* Insert(BST*, int );
void Inorder(BST*);
};
BST::BST()
: data(0)
, left(NULL)
, right(NULL)
{
}
BST::BST( int value)
{
data = value;
left = right = NULL;
}
BST* BST::Insert(BST* root, int value)
{
if (!root) {
return new BST(value);
}
if (value > root->data) {
root->right = Insert(root->right, value);
}
else if (value < root->data) {
root->left = Insert(root->left, value);
}
return root;
}
void BST::Inorder(BST* root)
{
if (!root) {
return ;
}
Inorder(root->left);
cout << root->data << " " ;
Inorder(root->right);
}
int main()
{
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
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
struct node* newNode( int item)
{
struct node* temp
= ( struct node*) malloc ( sizeof ( struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder( struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf ( "%d " , root->key);
inorder(root->right);
}
}
struct node* insert( struct node* node, int key)
{
if (node == NULL)
return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
int main()
{
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
insert(root, 80);
inorder(root);
return 0;
}
|
Java
import java.io.*;
public class BinarySearchTree {
class Node {
int key;
Node left, right;
public Node( int item)
{
key = item;
left = right = null ;
}
}
Node root;
BinarySearchTree() { root = null ; }
BinarySearchTree( int value) { root = new Node(value); }
void insert( int key) { root = insertRec(root, key); }
Node insertRec(Node root, int key)
{
if (root == null ) {
root = new Node(key);
return root;
}
else if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
void inorder() { inorderRec(root); }
void inorderRec(Node root)
{
if (root != null ) {
inorderRec(root.left);
System.out.print(root.key + " " );
inorderRec(root.right);
}
}
public static void main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert( 50 );
tree.insert( 30 );
tree.insert( 20 );
tree.insert( 40 );
tree.insert( 70 );
tree.insert( 60 );
tree.insert( 80 );
tree.inorder();
}
}
|
Python3
class Node:
def __init__( self , key):
self .left = None
self .right = None
self .val = key
def insert(root, key):
if root is None :
return Node(key)
else :
if root.val = = key:
return root
elif root.val < key:
root.right = insert(root.right, key)
else :
root.left = insert(root.left, key)
return root
def inorder(root):
if root:
inorder(root.left)
print (root.val, end = " " )
inorder(root.right)
if __name__ = = '__main__' :
r = Node( 50 )
r = insert(r, 30 )
r = insert(r, 20 )
r = insert(r, 40 )
r = insert(r, 70 )
r = insert(r, 60 )
r = insert(r, 80 )
inorder(r)
|
C#
using System;
class BinarySearchTree {
public class Node {
public int key;
public Node left, right;
public Node( int item)
{
key = item;
left = right = null ;
}
}
Node root;
BinarySearchTree() { root = null ; }
BinarySearchTree( int value) { root = new Node(value); }
void insert( int key) { root = insertRec(root, key); }
Node insertRec(Node root, int key)
{
if (root == null ) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
void inorder() { inorderRec(root); }
void inorderRec(Node root)
{
if (root != null ) {
inorderRec(root.left);
Console.Write(root.key + " " );
inorderRec(root.right);
}
}
public static void Main(String[] args)
{
BinarySearchTree tree = new BinarySearchTree();
tree.insert(50);
tree.insert(30);
tree.insert(20);
tree.insert(40);
tree.insert(70);
tree.insert(60);
tree.insert(80);
tree.inorder();
}
}
|
Javascript
<script>
class Node {
constructor(item) {
this .key = item;
this .left = this .right = null ;
}
}
var root = null ;
function insert(key) {
root = insertRec(root, key);
}
function insertRec(root, key) {
if (root == null ) {
root = new Node(key);
return root;
}
if (key < root.key)
root.left = insertRec(root.left, key);
else if (key > root.key)
root.right = insertRec(root.right, key);
return root;
}
function inorder() {
inorderRec(root);
}
function inorderRec(root)
{
if (root != null ) {
inorderRec(root.left);
document.write(root.key+ "<br/>" );
inorderRec(root.right);
}
}
insert(50);
insert(30);
insert(20);
insert(40);
insert(70);
insert(60);
insert(80);
inorder();
</script>
|
Output
20 30 40 50 60 70 80
Time Complexity:
- The worst-case time complexity of insert operations is O(h) where h is the height of the Binary Search Tree.
- In the worst case, we may have to travel from the root to the deepest leaf node. The height of a skewed tree may become n and the time complexity of insertion operation may become O(n).
Auxiliary Space: The auxiliary space complexity of insertion into a binary search tree is O(1)
Insertion in Binary Search Tree using Iterative approach:
Instead of using recursion, we can also implement the insertion operation iteratively using a while loop. Below is the implementation using a while loop.
C++
#include <bits/stdc++.h>
using namespace std;
class Node {
public :
int val;
Node* left;
Node* right;
Node( int val)
: val(val)
, left(NULL)
, right(NULL)
{
}
};
void insert(Node*& root, int key)
{
Node* node = new Node(key);
if (!root) {
root = node;
return ;
}
Node* prev = NULL;
Node* temp = root;
while (temp) {
if (temp->val > key) {
prev = temp;
temp = temp->left;
}
else if (temp->val < key) {
prev = temp;
temp = temp->right;
}
}
if (prev->val > key)
prev->left = node;
else
prev->right = node;
}
void inorder(Node* root)
{
Node* temp = root;
stack<Node*> st;
while (temp != NULL || !st.empty()) {
if (temp != NULL) {
st.push(temp);
temp = temp->left;
}
else {
temp = st.top();
st.pop();
cout << temp->val << " " ;
temp = temp->right;
}
}
}
int main()
{
Node* root = NULL;
insert(root, 30);
insert(root, 50);
insert(root, 15);
insert(root, 20);
insert(root, 10);
insert(root, 40);
insert(root, 60);
inorder(root);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
BST tree = new BST();
tree.insert( 30 );
tree.insert( 50 );
tree.insert( 15 );
tree.insert( 20 );
tree.insert( 10 );
tree.insert( 40 );
tree.insert( 60 );
tree.inorder();
}
}
class Node {
Node left;
int val;
Node right;
Node( int val) { this .val = val; }
}
class BST {
Node root;
public void insert( int key)
{
Node node = new Node(key);
if (root == null ) {
root = node;
return ;
}
Node prev = null ;
Node temp = root;
while (temp != null ) {
if (temp.val > key) {
prev = temp;
temp = temp.left;
}
else if (temp.val < key) {
prev = temp;
temp = temp.right;
}
}
if (prev.val > key)
prev.left = node;
else
prev.right = node;
}
public void inorder()
{
Node temp = root;
Stack<Node> stack = new Stack<>();
while (temp != null || !stack.isEmpty()) {
if (temp != null ) {
stack.add(temp);
temp = temp.left;
}
else {
temp = stack.pop();
System.out.print(temp.val + " " );
temp = temp.right;
}
}
}
}
|
Python3
class GFG:
@staticmethod
def main(args):
tree = BST()
tree.insert( 30 )
tree.insert( 50 )
tree.insert( 15 )
tree.insert( 20 )
tree.insert( 10 )
tree.insert( 40 )
tree.insert( 60 )
tree.inorder()
class Node:
left = None
val = 0
right = None
def __init__( self , val):
self .val = val
class BST:
root = None
def insert( self , key):
node = Node(key)
if ( self .root = = None ):
self .root = node
return
prev = None
temp = self .root
while (temp ! = None ):
if (temp.val > key):
prev = temp
temp = temp.left
elif (temp.val < key):
prev = temp
temp = temp.right
if (prev.val > key):
prev.left = node
else :
prev.right = node
def inorder( self ):
temp = self .root
stack = []
while (temp ! = None or not ( len (stack) = = 0 )):
if (temp ! = None ):
stack.append(temp)
temp = temp.left
else :
temp = stack.pop()
print ( str (temp.val) + " " , end = "")
temp = temp.right
if __name__ = = "__main__" :
GFG.main([])
|
C#
using System;
using System.Collections.Generic;
public class GFG {
public static void Main(String[] args)
{
BST tree = new BST();
tree.insert(30);
tree.insert(50);
tree.insert(15);
tree.insert(20);
tree.insert(10);
tree.insert(40);
tree.insert(60);
tree.inorder();
}
}
public class Node {
public Node left;
public int val;
public Node right;
public Node( int val) { this .val = val; }
}
public class BST {
public Node root;
public void insert( int key)
{
Node node = new Node(key);
if (root == null ) {
root = node;
return ;
}
Node prev = null ;
Node temp = root;
while (temp != null ) {
if (temp.val > key) {
prev = temp;
temp = temp.left;
}
else if (temp.val < key) {
prev = temp;
temp = temp.right;
}
}
if (prev.val > key)
prev.left = node;
else
prev.right = node;
}
public void inorder()
{
Node temp = root;
Stack<Node> stack = new Stack<Node>();
while (temp != null || stack.Count != 0) {
if (temp != null ) {
stack.Push(temp);
temp = temp.left;
}
else {
temp = stack.Pop();
Console.Write(temp.val + " " );
temp = temp.right;
}
}
}
}
|
Javascript
class Node {
constructor(val) {
this .left = null ;
this .val = val;
this .right = null ;
}
}
class BST {
constructor() {
this .root = null ;
}
insert(key) {
let node = new Node(key);
if ( this .root == null ) {
this .root = node;
return ;
}
let prev = null ;
let temp = this .root;
while (temp != null ) {
if (temp.val > key) {
prev = temp;
temp = temp.left;
} else if (temp.val < key) {
prev = temp;
temp = temp.right;
}
}
if (prev.val > key) prev.left = node;
else prev.right = node;
}
inorder() {
let temp = this .root;
let stack = [];
while (temp != null || stack.length > 0) {
if (temp != null ) {
stack.push(temp);
temp = temp.left;
} else {
temp = stack.pop();
console.log(temp.val + " " );
temp = temp.right;
}
}
}
}
let tree = new BST();
tree.insert(30);
tree.insert(50);
tree.insert(15);
tree.insert(20);
tree.insert(10);
tree.insert(40);
tree.insert(60);
tree.inorder();
|
Output
10 15 20 30 40 50 60
The time complexity of inorder traversal is O(n), as each node is visited once.
The Auxiliary space is O(n), as we use a stack to store nodes for recursion.
Related Links:
Share your thoughts in the comments
Please Login to comment...