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 C++ 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
- Lowest Common Ancestor in a Binary Tree | Set 1
- Convert a Binary Tree to a Circular Doubly Link List
- Count pairs in a binary tree whose sum is equal to a given value x
- Mu Sigma Interview On Campus
- Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment
- Bubble Sort On Doubly Linked List
- Reverse nodes of a linked list without affecting the special characters