Given a Binary Tree, convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of Binary Tree.
Example 1 Input: 10 / \ 2 7 / \ 8 4 Output: 8 / \ 4 10 / \ 2 7 Example 2 Input: 10 / \ 30 15 / \ 20 5 Output: 15 / \ 10 20 / \ 5 30
Following is a 3 step solution for converting Binary tree to Binary Search Tree.
1) Create a temp array arr that stores inorder traversal of the tree. This step takes O(n) time.
2) Sort the temp array arr. Time complexity of this step depends upon the sorting algorithm. In the following implementation, Quick Sort is used which takes (n^2) time. This can be done in O(nLogn) time using Heap Sort or Merge Sort.
3) Again do inorder traversal of tree and copy array elements to tree nodes one by one. This step takes O(n) time.
Following is C implementation of the above approach. The main function to convert is highlighted in the following code.
Following is Inorder Traversal of the converted BST: 5 10 15 20 30
- Time Complexity: O(nlogn).
This is the complexity of the sorting algorithm which we are using after first in-order traversal, rest of the opertions take place in linear time.
- Auxiliary Space: O(n).
Use of data structure ‘array’ to store in-order traversal.
We will be covering another method for this problem which converts the tree using O(height of the tree) extra space.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
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.
- Binary Tree to Binary Search Tree Conversion using STL set
- Minimum swap required to convert binary tree to binary search tree
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Difference between Binary Tree and Binary Search Tree
- Convert a Binary Search Tree into a Skewed tree in increasing or decreasing order
- Count the Number of Binary Search Trees present in a Binary Tree
- Check if a binary tree is subtree of another binary tree using preorder traversal : Iterative
- Check whether a binary tree is a full binary tree or not | Iterative Approach
- Search a node in Binary Tree
- Sum of all the levels in a Binary Search Tree
- Make Binary Search Tree
- Floor in Binary Search Tree (BST)
- Binary Search Tree | Set 2 (Delete)
- Iterative Search for a key 'x' in Binary Tree
- Optimal Binary Search Tree | DP-24
- Binary Search Tree | Set 1 (Search and Insertion)
- Print all even nodes of Binary Search Tree
- Print all odd nodes of Binary Search Tree
- Double Threaded Binary Search Tree
- Inorder Successor in Binary Search Tree
Improved By : bidibaaz123