Given a binary tree, extract all its leaves into a doubly-linked list, i.e., remove all leaf nodes from the binary tree and construct a doubly linked list out of them.

The extraction should be by rearranging the pointers of the binary tree such that the left pointer should act as the previous pointer, and the right pointer should serve as the next pointer for the doubly linked list node.

 
The solution should process the left child before its right child for each tree node. For example,

Binary Tree – Extract Leaves

Practice this problem

1. Using Inorder Traversal

We can solve the problem in a single traversal of the tree by performing an inorder traversal on the tree and keeping track of the tail of the doubly linked list. For each leaf node in the inorder traversal, set the left pointer to tail and tail’s right pointer to the current leaf node. Also, update the corresponding left or right pointer of the parent node to null to remove the leaf nodes from the binary tree.

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Extracted doubly linked list is 8 9 5 10 11 7
Preorder traversal of the final tree is 1 2 4 3 6

2. Using Reverse Inorder Traversal

The above solution processes the leaf nodes from left to right and efficiently inserts the leaf nodes at the end of the doubly linked list. It does that by maintaining a pointer to the linked list’s tail. We can avoid maintaining this pointer using reverse inorder traversal where the right subtree is processed before the left subtree. Now, we can easily insert each encountered node at the beginning of the list.

Following is the C++, Java, and Python program that demonstrates it:

C++


Download  Run Code

Java


Download  Run Code

Python


Download  Run Code

Output:
 
Extracted doubly linked list is 8 9 5 10 11 7
Preorder traversal of the final tree is 1 2 4 3 6

The time complexity of both above-discussed methods is O(n) and requires O(h) extra space for the call stack, where n is the total number of nodes and h is the height of the binary tree.