Sunday, July 11, 2010

Convert a binary search tree to a sorted double linked list

////////////////////////////////////////////////////////////////
// Covert a sub binary-search-tree into a sorted double-linked list
// Input: root - the head of the sub tree
// isRight - whether root is the right child of its parent
// Output: if isRight is true, return the least node in the sub-tree
// else return the greatest node in the sub-tree
////////////////////////////////////////////////////////////////

typedef struct tree_node
{
int value;
struct tree_node * left;
struct tree_node * right;
} node;

typedef enum{false=0,true=1} bool;

node * ToDoubleLinkedlist(node *,bool);

node * ToDoubleLinkedlist(node * root,bool isRight)
{
if(!root)
{
return NULL;
}

node * left=NULL;
node * right=NULL;

if(root->left)
{
left=ToDoubleLinkeList(root->left,false);

if(left)
{
root->left=left;
left->right=root;
}
}

if(root->right)
{
right=ToDoubleLinkedList(root->right,true);

if(right)
{
root->right=right;
right->left=root;
}
}

node * temp=root;

if(isRight)
{
while(temp)
{
temp=root->left;
}
}
else
{
while(temp)
{
temp=root->right
}
}

return temp;

}

No comments:

Post a Comment