Lets suppose we have a binary tree . Tree node structure is as
struct node
{
int val ;
struct node *left , *right ;
}
Now we have to sort the tree in level order manner . For example lets suppose we have original tree like this
root = 6
root->left = 1
root->right = 9
root->left->left = 8
root->right->right = 2
Then after applying level order sorting , our tree will be
root = 1
root->left = 2
root->right = 6
root->left->left = 8
root->right->right = 9
One way of doing this problem is just take all the values in a array and apply any of the standard sorting algorithm and then put back the values in tree in level order traversal manner. This solution is not efficient in term of space and time both.
What algorithm can I use to decrease operations and memory usage from my proposed plan? Is there a more efficient algorithm to do this without the use of a sorted array?
Level order sorting :
Level order sorting means if you do level order traversal of the tree then you should get a sorted non-decreasing sequence .
Constraint :
Shape of the tree should not alter that is if in original tree left child of the root does not have right child (as in my example) then after sorting too, it should not has right child .