![]() |
VOOZH | about |
Given a Binary Tree (BT), the task is to convert it to a Doubly Linked List (DLL) in place. The left and right pointers in nodes will be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be the same as the order of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL.
Examples:
Input:
👁 Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-ex-1Output:
👁 Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-1
Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.
Input:
👁 Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-ex-2Output:
👁 Convert-Binary-Tree-to-Doubly-Linked-List-using-inorder-traversal-2
Explanation: The above binary tree is converted into doubly linked list where left pointer of the binary tree node act as the previous node and right pointer of the binary tree node act as the next node.
Approach:
In the following implementation, we traverse the tree in inorder fashion. We add nodes at the beginning of current linked list and update head of the list using pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree before the left subtree. i.e. do a reverse inorder traversal.
0 1 2 3 4 5 6 7 8 9
Time Complexity: O(n), as the solution does a single traversal of given Binary Tree.
Auxiliary Space: O(n)
Related articles: