Open In App

Binary Tree to Binary Search Tree Conversion using STL set

Last Updated : 01 Oct, 2024
Comments
Improve
Suggest changes
19 Likes
Like
Report

Given a Binary Tree, the task is to convert it to a Binary Search Tree. The conversion must be done in such a way that keeps the original structure of the Binary Tree. 

Example:

Input:

Binary-Tree-to-Binary-Search-Tree-Conversion

Output:

Binary-Tree-to-Binary-Search-Tree-Conversion-3


Explanation: The above Binary tree is converted to Binary Search tree by keeping the original structure of Binary Tree. 

Approach:

The idea is to recursively traverse the binary tree and insert the value of nodes into a hash set. Then, traverse the tree in in-order manner and pop the smallest value from set and update the value of node to the popped value.

  • Copy the items of binary tree in a set while doing inorder traversal. This takes O(n log n) time. Note that set in C++ STL is implemented using a Self Balancing Binary Search Tree like Red Black Tree, AVL Tree, etc
  • There is no need to sort the set as sets in C++ are implemented using Self-balancing binary search trees due to which each operation such as insertion, searching, deletion, etc takes O(log n) time.
  • Now simply copy the items of set one by one from beginning to the tree while doing inorder traversal of the tree. Care should be taken as when copying each item of set from its beginning, we first copy it to the tree while doing inorder traversal, then remove it from the set as well.

Below is the implementation of the above approach:

C++
Java Python C# JavaScript

Output
2 4 7 8 10 

Time Complexity: O(nlogn)
Auxiliary Space: O(n)

Related article:



Next Article

Similar Reads