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.

For example,
Binary Tree - Extract Leaves

The problem can be solved in a single traversal of the tree by performing an in-order traversal on the tree and keeping track of the tail of the doubly linked list. Each leaf node in the in-order traversal, set its 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 Double Linked list: 8 9 5 10 11 7
Preorder traversal of final tree: 1 2 4 3 6

Download   Run Code

Download   Run Code

Download   Run Code

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 maintains a pointer to the linked list’s tail. We can avoid maintaining this pointer by reverse-in-order 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 Double Linked list: 8 9 5 10 11 7
Preorder traversal of final tree: 1 2 4 3 6

Download   Run Code

Download   Run Code

Download   Run Code

source