VOOZH about

URL: https://www.geeksforgeeks.org/dsa/split-a-bst-into-two-balanced-bsts-based-on-a-value-k/

⇱ Split a BST into two balanced BSTs based on a value K - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Split a BST into two balanced BSTs based on a value K

Last Updated : 12 Jul, 2025

Given a Binary Search tree and an integer K, we have to split the tree into two Balanced Binary Search Tree, where BST-1 consists of all the nodes which are less than K and BST-2 consists of all the nodes which are greater than or equal to K.
Note: The arrangement of the nodes may be anything but both BST should be Balanced.

Examples: 

Input:
 40 
 / \ 
 20 50 
 / \ \ 
 10 35 60
 / / 
 25 55 
K = 35
Output:
First BST: 10 20 25
Second BST: 35 40 50 55 60
Explanation:
After splitting above BST
about given value K = 35
First Balanced Binary Search Tree is 
 20 
 / \ 
 10 25 
Second Balanced Binary Search Tree is
 50 
 / \ 
 35 55 
 \ \ 
 40 60
OR
 40 
 / \ 
 35 55 
 / \ 
 50 60

Input:
 100 
 / \ 
 20 500 
 / \ 
 10 30 
 \ 
 40 
K = 50
Output:
First BST: 10 20 30 40
Second BST: 100 500
Explanation:
After splitting above BST 
about given value K = 50
First Balanced Binary Search Tree is 
 20 
 / \ 
 10 30 
 \
 40
Second Balanced Binary Search Tree is
 100 
 \ 
 500 

Approach:  

Below is the implementation of the above approach:


Output: 
Original BST : 2 3 4 5 6 7 8 
First BST : 2 3 4 
Second BST : 5 6 7 8

 

Time Complexity: where n is the number of nodes in the BST. This is because the function storeInorder() traverses through all the nodes of the BST inorder and the function createBST() traverses through all the nodes of the balanced BST that it creates.
Auxiliary Space: where n is the number of nodes in the BST. This is because an array of size n is created to store the inorder traversal of the BST. Additionally, a new balanced BST is created from the inorder traversal, which also requires space.

Comment