Showing posts with label tree. Show all posts
Showing posts with label tree. Show all posts

Tuesday, April 13, 2010

Converting BST to sorted Doubly Linked List

Today, one of my friend asked how to convert a Binary Search Tree to sorted Doubly Linked List. He came across this problem while preparing for interview. I then began to dig what I could remember about BST. I had learnt from my Data Structures course in college that most tree problems boil down to tree traversal problems. So I started thinking along that line and suddenly came out with a solution. The idea is to traverse the tree In Order and adjust the pointers accordingly. The code for this is pretty straight forward.


Node *last_left = 0;

void traverse(Node * node)
{
if(node == 0)
return;
//traverse left tree
traverse(node->left_);

//adjust the left and right pointers (left points to previous
//and right points to next)
//in terms of doubly linked list
if(last_left != 0){
last_left->right_ = node;
node ->left_ = last_left;
last_left = node;
}
else
last_left = node;

//traverse right subtree
traverse(node->right_);
}