Open In App

Insertion in Binary Search Tree (BST)

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
12 Likes
Like
Report

Given a BST, the task is to insert a new node in this BST.

Example:

Insertion-in-BST

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:

  • Initilize the current node (say, currNode or node) with root node
  • Compare the key with the current node.
  • Move left if the key is less than or equal to the current node value.
  • Move right if the key is greater than current node value.
  • Repeat steps 2 and 3 until you reach a leaf node.
  • Attach the new key as a left or right child based on the comparison with the leaf node's value.

Follow the below illustration for a better understanding:

Insertion in Binary Search Tree using Recursion:

Below is the implementation of the insertion operation using recursion.

C++14
C Java Python C# JavaScript

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(h), due to recursive stack.

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++
C Java Python C# JavaScript

Output
20 30 40 50 60 70 80 

The time complexity of inorder traversal is O(h), where h is the height of the tree.
The Auxiliary space is O(1)

Related Links: 


Insert In BST (Python)
Visit Course explore course icon
Article Tags :

Similar Reads