Reputation: 31
How can you convert Binary Tree to Binary Search Tree with O(1) extra space ?
Upvotes: 2
Views: 1793
Reputation: 2759
Convert Binary Tree to a doubly linked list- can be done inplace in O(n) Then sort it using merge sort, nlogn Convert the list back to a tree - O(n)
Simple nlogn solution.
Upvotes: -1
Reputation: 391286
Converting an unordered binary tree into an ordered binary search tree is trivial, but a bit more difficult to do fast.
Here's a naive implementation that should satisfy your criteria, I will not describe the actual steps to take, just the overall algorithm.
You should require only a few variables, like the parent of the leaf node you're unlinking (unless the nodes has parent-links), the root node of the new tree, and a couple of temporary variables, all within your O(1) space criteria.
This will not produce an optimal binary search tree. For that you need to either sort the nodes before adding them, and adding them in the right order, or use a balancing binary search tree, like a red-black tree or a splay tree.
Upvotes: 7