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
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- 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
- Print all pairs from two BSTs whose sum is greater than the given value
- Check if two given key sequences construct same BSTs
- Count pairs from two BSTs whose sum is equal to a given value x
- Merge two BSTs with constant extra space
- Merge two BSTs with limited extra space
- Find pairs with given sum such that pair elements lie in different BSTs
- Total number of BSTs using array elements
- Check for Identical BSTs without building the trees
- Generate two BSTs from the given array such that maximum height among them is minimum
- Find a pair with given sum in a Balanced BST
- Convert a normal BST to 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
- Find the minimum value to be added so that array becomes balanced
- Count Balanced Binary Trees of Height h
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.