![]() |
VOOZH | about |
Given a Binary Tree, The task is to convert it to a Doubly Linked List keeping the same order.
The following two different solutions have been discussed for this problem.
Convert a given Binary Tree to a Doubly Linked List | Set 1
Convert a given Binary Tree to a Doubly Linked List | Set 2
Approach: Below is the idea to solve the problem:
The idea is to do in-order traversal of the binary tree. While doing inorder traversal, keep track of the previously visited node in a variable, say prev. For every visited node, make it next to the prev and set previous of this node as prev.
Below is the implementation of the above approach:
25 12 30 10 36 15
Note: The use of static variables like above is not a recommended practice, here static is used for simplicity. Imagine if the same function is called for two or more trees. The old value of prev would be used in the next call for a different tree. To avoid such problems, we can use a double-pointer or a reference to a pointer.
Time Complexity: O(N), The above program does a simple inorder traversal, so time complexity is O(N) where N is the number of nodes in a given Binary tree.
Auxiliary Space: O(N), For recursion call stack.
Do iterative inorder traversal and maintain a prev pointer to point the last visited node then point current node's perv to prev and prev's next to current node.
Below is the implementation of the above approach:
25 12 30 10 36 15
Time complexity: O(N)
Auxiliary Space: O(N)
The idea is to keep track of previous node while doing Inorder tree traversal using Morris Traversal. This removes the need for a recursion call stack or a stack thus reducing space complexity
25 12 30 10 36 15
Time complexity: O(N)
Auxiliary Space: O(1)