![]() |
VOOZH | about |
Given a Binary Tree, 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 (the leftmost node in Binary Tree) 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:
The idea involves converting a Binary Tree to a Doubly Linked List (DLL) in place by first fixing the left pointers during an in-order traversal to point to the previous node, then fixing the right pointers by traversing the modified tree in reverse using the left pointers to point to the next node in the DLL.
Step by step approach:
25 12 30 10 36 15
Time Complexity: O(n), where n is the number of nodes in Binary tree.
Auxiliary Space: O(n)
Related Article: