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.
Following two different solutions have been discussed for this problem.
Convert a given Binary Tree to Doubly Linked List | Set 1
Convert a given Binary Tree to Doubly Linked List | Set 2
In this post, a third solution is discussed which seems to be the simplest of all. The idea is to do inorder 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 of prev and previous of this node as prev.
Thanks to rahul, wishall and all other readers for their useful comments on the above two posts.
Following is the implementation of this solution.
25 12 30 10 36 15
Note that use of static variables like above is not a recommended practice (we have used static for simplicity). Imagine a situation where same function is called for two or more trees, the old value of prev would be used in next call for a different tree. To avoid such problems, we can use double pointer or reference to a pointer.
Time Complexity: The above program does a simple inorder traversal, so time complexity is O(n) where n is the number of nodes in given binary tree.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 1
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Convert a Binary Tree to a Circular Doubly Link List
- Extract Leaves of a Binary Tree in a Doubly Linked List
- Convert an Array to a Circular Doubly Linked List
- Create a Doubly Linked List from a Ternary Tree
- Flatten a binary tree into linked list | Set-3
- Flatten a binary tree into linked list | Set-2
- Flatten a binary tree into linked list
- Difference between Singly linked list and Doubly linked list
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
Improved By : shrikanth13