Split a BST into two balanced BSTs based on a value K
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.
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
- First store the inorder traversal of given BST in an array
- Then, split this array about given value K
- Now construct first balanced BST by first splitting part and second BST by second splitting part, using the approach used in this article.
Below is the implementation of the above approach:
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.
Please Login to comment...