• Courses
  • Tutorials
  • Jobs
  • Practice
  • Contests
August 02, 2022 |920 Views
Extract Leaves of a Binary Tree in a Doubly Linked List
Description
Discussion

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.  

We need to traverse all leaves and connect them by changing their left and right pointers. We also need to remove them from the 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 the current linked list and update the head of the list using the 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.  

Let the following be input binary tree
       1
    /     \
   2       3
  / \       \
 4   5       6
/ \         / \
7   8       9   10


Output:
Doubly Linked List
785910

Extract Leaves of a Binary Tree in a Doubly Linked List: https://www.geeksforgeeks.org/connect-leaves-doubly-linked-list/

Read More