Convert a given binary tree into a BST (Binary Search Tree) by keeping its original structure intact.

For example, consider a binary tree shown on the left below. The solution should convert it into a BST shown on the right.

Convert binary tree into a BST

Practice this problem

The idea is to traverse the binary tree and store its keys in a set. We know that an inorder traversal of a binary search tree returns the nodes in sorted order, so traverse the tree again in an inorder fashion and put the keys present in the set (in sorted order) back to their correct position in the BST.

The advantage of using a set over an array is that the keys are always retrieved in sorted order from the set. If an array is used, sort the keys first before inserting them back.

 
Following is the C++, Java, and Python implementation of the idea:

C++


Download  Run Code

Output:

2 3 4 5 6 8 10

Java


Download  Run Code

Output:

2 3 4 5 6 8 10

Python


Download  Run Code

Output:

2 3 4 5 6 8 10

The time complexity of the above solution is O(n.log(n)), where n is the size of the BST, and requires linear space for storing the tree nodes.