VOOZH about

URL: https://www.geeksforgeeks.org/dsa/insertion-in-binary-search-tree/

⇱ Insertion in Binary Search Tree (BST) - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Insertion in Binary Search Tree (BST)

Last Updated : 8 Dec, 2025

Given the root of a Binary Search Tree, we need to insert a new node with given value in the BST. All the nodes have distinct values in the BST and we may assume that the the new value to be inserted is not present in BST.

Example:

👁 Insertion-in-BST

A new key is inserted at the position that maintains the BST property. We start from the root and move downward: if the key is smaller, go left; if larger, go right. We continue until we find an unoccupied spot where the node can be placed without violating the BST property, and insert it there as a new leaf.

Insertion in Binary Search Tree using Recursion:


Output
22 
12 30 
8 20 N 30 
N N 15 N N N 

Time Complexity: O(h)

  • 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: 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, using the same idea as above.


Output
22 
12 30 
8 20 N 30 
N N 15 N N N 

Time complexity: O(h), where h is the height of the tree.
Auxiliary space: O(1)

Related Links: 

Comment
Article Tags:
Article Tags: