Convert Binary Search Tree (BST) to Sorted Doubly-Linked List

Convert a BST to a sorted circular doubly-linked list in-place. Think of the left and right pointers as synonymous to the previous and next pointers in a doubly-linked list.

C++:
01 void enlist(Node ** head, Node *ennode)
02 {
03     if((*head)==NULL){
04         *head=ennode;
05         (*head)->left=ennode;
06         (*head)->right=ennode;
07     }
08     else{
09         ennode->left=(*head)->left;
10         (*head)->left->right=ennode;
11         ennode->right=(*head);
12         (*head)->left=ennode;
13     }
14 }
15 
16 
17 void create_dblist(Node ** head, Node *root)
18 {
19     if(root==NULL)
20         return;
21     Node *tmp;
22     tmp=root->right;
23     create_dblist(head,root->left);
24     enlist(head,root);
25     create_dblist(head,tmp);
26 }
Advertisements
This entry was posted in Array and linked list, Tree. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s