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.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Tree with N nodes and K leaves such that distance between farthest leaves is minimized
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- Difference between Singly linked list and Doubly linked list
- 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 3
- Convert a given Binary Tree to Doubly Linked List | Set 4
- Convert a Binary Tree into Doubly Linked List in spiral fashion
- Convert a given Binary Tree to Circular Doubly Linked List | Set 2
- Construct a Doubly linked linked list from 2D Matrix
- Find the maximum path sum between two leaves of a binary tree
- Find sum of all left leaves in a given Binary Tree
- Print all nodes in a binary tree having K leaves
- Find sum of all right leaves in a given Binary Tree
- Minimum sum path between two leaves of a binary tree
- Height of binary tree considering even level leaves only
- Create a Doubly Linked List from a Ternary Tree
- Convert a Binary Tree to a Circular Doubly Link List
- Mimimum number of leaves required to be removed from a Tree to satisfy the given condition