![]() |
VOOZH | about |
Given a Binary Tree (BT), convert it to a Doubly Linked List (DLL). 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 the same as in Inorder for the given Binary Tree. The first node of Inorder traversal must be the head node of the DLL.
Examples:
Input:
1
/ \
3 2
Output:
Actual order: 3 1 2
Reverse order: 2 1 3
Explanation: The head of the linked list will be 3 and the last element will be 2.
DLL will be 3 <=> 1 <=> 2Input:
10
/ \
20 30
/ \
40 60
Output:
Actual order: 40 20 60 10 30
Reverse order: 30 10 60 20 40
Below are several approaches that have been discussed earlier:
Approach:
The above approaches use recursion or stack to get the Inorder Traversal. This approach is based on Morris Traversal to find Inorder Traversal which is iterative and has a space complexity of O(1).
The idea is that we will first create a singly linked list while doing Morris Traversal and later convert it into a doubly-linked list by setting the left pointer of every node to the previous node in inorder.
Follow the steps mentioned below to implement the idea:
Below is the implementation of the above approach.
Actual order: 40 20 60 10 30 Reverse Order: 30 10 60 20 40
Time Complexity: O(N)
Auxiliary Space: O(1)