Given a binary tree that is only one swap away from becoming a BST, convert it into a BST in a single traversal.

For example, consider the binary tree shown on the left below. The solution should convert it into a BST shown on the right by swapping nodes 2 and 4.

 
Fix a Binary Tree

Practice this problem

We know that an inorder traversal of a binary search tree returns the nodes in sorted order. The idea is to perform inorder traversal on a given binary tree and keep track of the last visited node while traversing the tree. Check whether its key is smaller compared to the current key or not and mark the nodes where this property is violated and later swap them.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

8 10 12 15 16 20 25

Java


Download  Run Code

Output:

8 10 12 15 16 20 25

Python


Download  Run Code

Output:

8 10 12 15 16 20 25

The time complexity of the above solution is O(n), where n is the size of the BST, and requires space proportional to the tree’s height for the call stack.