Given a Binary Tree, extract all leaves of it in a Doubly Linked List (DLL). Note that the DLL need to be created in-place. Assume that the node structure of DLL and Binary Tree is same, only the meaning of left and right pointers are different. In DLL, left means previous pointer and right means next pointer.
Let the following be input binary tree 1 / \ 2 3 / \ \ 4 5 6 / \ / \ 7 8 9 10 Output: Doubly Linked List 785910 Modified Tree: 1 / \ 2 3 / \ 4 6
We need to traverse all leaves and connect them by changing their left and right pointers. We also need to remove them from Binary Tree by changing left or right pointers in parent nodes. There can be many ways to solve this. In the following implementation, we add leaves at the beginning of current linked list and update head of the list using pointer to head pointer. Since we insert at the beginning, we need to process leaves in reverse order. For reverse order, we first traverse the right subtree then the left subtree. We use return values to update left or right pointers in parent nodes.
Inorder Trvaersal of given Tree is: 7 4 8 2 5 1 3 9 6 10 Extracted Double Linked list is: 7 8 5 9 10 Inorder traversal of modified tree is: 4 2 1 3 6
Time Complexity: O(n), the solution does a single traversal of given Binary Tree.
This article is contributed by Chandra Prakash. 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 1
- Convert a given Binary Tree to Doubly Linked List | Set 2
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a given Binary Tree to Doubly Linked List | Set 3
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Create a Doubly Linked List from a Ternary Tree
- Convert a Binary Tree to a Circular Doubly Link List
- Flatten a binary tree into linked list
- Flatten a binary tree into linked list | Set-2
- Flatten a binary tree into linked list | Set-3
- Difference between Singly linked list and Doubly linked list
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- Find sum of all right leaves in a given Binary Tree
- Construct Complete Binary Tree from its Linked List Representation