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: 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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Nodes from given two BSTs with sum equal to X
- Check if two BSTs contain same set of elements
- Construct all possible BSTs for keys 1 to N
- Check if two given key sequences construct same BSTs
- Count pairs from two BSTs whose sum is equal to a given value x
- Print all pairs from two BSTs whose sum is greater than the given value
- Merge two BSTs with limited extra space
- Total number of BSTs using array elements
- Find pairs with given sum such that pair elements lie in different BSTs
- Check for Identical BSTs without building the trees
- Merge two BSTs with constant extra space
- Generate two BSTs from the given array such that maximum height among them is minimum
- Convert a normal BST to Balanced BST
- Find a pair with given sum in a Balanced BST
- Sorted Array to Balanced BST
- Pairs involved in Balanced Parentheses
- Sorted Linked List to Balanced BST
- Find if there is a triplet in a Balanced BST that adds to zero
- Check for balanced parentheses in an expression | O(1) space
- Find the lexicographical next balanced bracket sequence
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.