I have a binary tree of some shape. I want to Convert it to BST search tree of same shape. Is it possible?
I tried methods like –
- Do In-order traversal of Binary Tree & put contents into an array. Then map this into a BST keeping in mind the condition (left val <= root <= right val). This works for some cases but faile for others.
P.S.: I had a look at this – Binary Trees question. Checking for similar shape. But It’s easy to compare 2 BST’s for similarity in shape.
The short answer is: you can’t. A BST requires that the nodes follow the rule left <= current < right. In the example you linked: http://upload.wikimedia.org/wikipedia/commons/f/f7/Binary_tree.svg, if you try and build a BST with the same shap you’ll find that you can’t.
However if you want to stretch the definition of a BST so that it allows left <= current <= right (notice that here current <= right is allowed, as apposed to the stricter definition) you can. Sort all the elements and stick them in an array. Now do an in-order traversal, replacing the values at nodes with each element in your array. Here’s some pseudo code:
The result won’t be a true BST however. If you want a true BST that’s as close to the original shape as possible, then you again put the elements in a sorted array but this time insert them into a BST. The order in which you insert them is defined by the sizes of the subtrees of the original tree. Here’s some pseudo-code:
This won’t guarantee that the shape is the same however.