Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a BST two nodes are randomly swapped we need to find those two nodes and swap them back

Given a binary search tree, in which any two nodes are swapped. So we need to find those two nodes and swap them back(we need to swap the nodes, not the data)

I tried to do this by making an additional array which has the inorder traversal of the tree and also saves the pointer to each node. Then we just traverse the array and find the two nodes that are not in the sorted order, now these two nodes are searched in the tree and then swapped

So my question is how to solve this problem in O(1) space ?

like image 335
Aman Singhal Avatar asked Aug 06 '12 08:08

Aman Singhal


1 Answers

In order traversal on a BST gives you a traversal on the elements, ordered.
You can use an in-order traversal, find the two out of place elements (store them in two pointers) and swap them back.

This method is actually creating the array you described on the fly, without actually creating it.

Note that however, space consumption is not O(1), it is O(h) where h is the height of the tree, due to the stack trace. If the tree is balanced, it will be O(logn)

like image 187
amit Avatar answered Nov 15 '22 07:11

amit