Problem:Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL.The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the DLL.
This is well described in here and here .
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 |
/* Structure for tree and linked list struct Node { int data; // left is used as previous and right is used // as next in DLL Node *left, *right; }; */ Node *BToDLLUtil(Node *root) { if(root==NULL) return root; if(root->left!=NULL) { Node *left=BToDLLUtil(root->left); while(left->right!=NULL) left=left->right; root->left=left; left->right=root; } if(root->right!=NULL) { Node *rit=BToDLLUtil(root->right); while(rit->left!=NULL) rit=rit->left; rit->left=root; root->right=rit; } return root; } // This function should convert a given Binary tree to Doubly // Linked List // root --> Root of Binary Tree // head_ref --> Pointer to head node of created doubly linked list void BToDLL(Node *root, Node **head_ref) { Node *newRoot = BToDLLUtil(root); while(newRoot->left) newRoot=newRoot->left; (*head_ref)=newRoot; } |