Recover Binary Search Tree

In this problem, we have given the root of a binary search tree (BST), where exactly two nodes of the tree were swapped by mistake. Write a code to recover binary search tree without changing its structure.

The solution using O(n) space is pretty straight forward. Can you solve this problem using constant space?

Let’s first discuss the property of binary search tree.

In a binary search tree, the value of all the nodes in the left sub-tree is less than the value of the root node. And the value of all the nodes in the right sub-tree is greater than or equal to the value of the root.

This condition will be recursively applied to all the left and right sub-trees of the root.

For Example –

Example 1 –

In this example, If we swap two nodes whose value is 2 and 3. We can recover the binary search tree.

Example 2 –

In second example, We have swap the nodes 1 and 3 then we get the binary search tree.

We have discussed the problem statement. Let’s think how we can approach this problem. How we can recover binary search tree using constant space? Also, I have added video tutorial link at the end of this post.

Recover Binary Search Tree using Inorder Traversal – Java Code

First, let’s start with the easiest approach then we will improve our solution.

To solve this problem, I am using the property that the inorder traversal of a binary search tree gives a value in a sorted order.

Inorder Traversal without Recursion

Programming questions on Binary Tree

The easiest approach is to traverse a tree using inorder traversal. Also, put the node values in an array or list. Once we are done with the traversal, then traverse the list and find the two values which are not in a sorted order.

Next step is to traverse a tree again and swap these two values.

Is it possible to solve this problem without using constant space? Let’s discuss our next approach in which we solve this problem using constant space.

Programming Video Tutorials

Recover Binary Search Tree using Constant Space – Java Code

Let’s optimize our previous approach. Instead of using extra array, we can find the two nodes which are not in correct order while traversing a tree using inorder traversal.

Tagged , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.