GeeksforGeeks » Miscellaneous
Convert a BST into a sorted doubly linked list (No extra space allowed)
(4 posts)-
node *BST_to_list ( Node *n) { if (!n) return NULL; Node *left = BST_to_list (n->left); Node *right = BST_to_list (n->right); Node *origLeft = left; // Left and Right trees have been converted to linked lists, // now merge them along with the current node. if (left) { while (left->left) // leftNode pointer becomes the next pointer in the DLL. left = left->left; left->left = node; } node->right = left; // rightNode pointer becomes the prev pointer in the DLL. node->left = right; if (right) right->right = node; return origLeft; } -
Node * conv(Node *N) { static Node *H=NULL; static Node *p=NULL; Node *t1=N->lc; Node *t2=N->rc; if(t1) conv(t1); if(!H) { H=N; p=N; } else { p->rc=N; N->lc=p; N->rc=NULL; p=N; } if(t2) conv(t2); return H; }
Reply
You must log in to post.