Extract Leaves of a Binary Tree in a Doubly Linked List
Last Updated :
23 Jul, 2025
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 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.
C++
// C++ program to extract leaves of
// a Binary Tree in a Doubly Linked List
#include <bits/stdc++.h>
using namespace std;
// Structure for tree and linked list
class Node
{
public:
int data;
Node *left, *right;
};
// Main function which extracts all
// leaves from given Binary Tree.
// The function returns new root of
// Binary Tree (Note that root may change
// if Binary Tree has only one node).
// The function also sets *head_ref as
// head of doubly linked list. left pointer
// of tree is used as prev in DLL
// and right pointer is used as next
Node* extractLeafList(Node *root, Node **head_ref)
{
// Base cases
if (root == NULL) return NULL;
if (root->left == NULL && root->right == NULL)
{
// This node is going to be added
// to doubly linked list of leaves,
// set right pointer of this node
// as previous head of DLL. We
// don't need to set left pointer
// as left is already NULL
root->right = *head_ref;
// Change left pointer of previous head
if (*head_ref != NULL) (*head_ref)->left = root;
// Change head of linked list
*head_ref = root;
return NULL; // Return new root
}
// Recur for right and left subtrees
root->right = extractLeafList(root->right, head_ref);
root->left = extractLeafList(root->left, head_ref);
return root;
}
// Utility function for allocating node for Binary Tree.
Node* newNode(int data)
{
Node* node = new Node();
node->data = data;
node->left = node->right = NULL;
return node;
}
// Utility function for printing tree in In-Order.
void print(Node *root)
{
if (root != NULL)
{
print(root->left);
cout<<root->data<<" ";
print(root->right);
}
}
// Utility function for printing double linked list.
void printList(Node *head)
{
while (head)
{
cout<<head->data<<" ";
head = head->right;
}
}
// Driver code
int main()
{
Node *head = NULL;
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
root->left->left->left = newNode(7);
root->left->left->right = newNode(8);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
cout << "Inorder Traversal of given Tree is:\n";
print(root);
root = extractLeafList(root, &head);
cout << "\nExtracted Double Linked list is:\n";
printList(head);
cout << "\nInorder traversal of modified tree is:\n";
print(root);
return 0;
}
// This code is contributed by rathbhupendra
C
// C program to extract leaves of a Binary Tree in a Doubly Linked List
#include <stdio.h>
#include <stdlib.h>
// Structure for tree and linked list
struct Node
{
int data;
struct Node *left, *right;
};
// Main function which extracts all leaves from given Binary Tree.
// The function returns new root of Binary Tree (Note that root may change
// if Binary Tree has only one node). The function also sets *head_ref as
// head of doubly linked list. left pointer of tree is used as prev in DLL
// and right pointer is used as next
struct Node* extractLeafList(struct Node *root, struct Node **head_ref)
{
// Base cases
if (root == NULL) return NULL;
if (root->left == NULL && root->right == NULL)
{
// This node is going to be added to doubly linked list
// of leaves, set right pointer of this node as previous
// head of DLL. We don't need to set left pointer as left
// is already NULL
root->right = *head_ref;
// Change left pointer of previous head
if (*head_ref != NULL) (*head_ref)->left = root;
// Change head of linked list
*head_ref = root;
return NULL; // Return new root
}
// Recur for right and left subtrees
root->right = extractLeafList(root->right, head_ref);
root->left = extractLeafList(root->left, head_ref);
return root;
}
// Utility function for allocating node for Binary Tree.
struct Node* newNode(int data)
{
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->left = node->right = NULL;
return node;
}
// Utility function for printing tree in In-Order.
void print(struct Node *root)
{
if (root != NULL)
{
print(root->left);
printf("%d ",root->data);
print(root->right);
}
}
// Utility function for printing double linked list.
void printList(struct Node *head)
{
while (head)
{
printf("%d ", head->data);
head = head->right;
}
}
// Driver program to test above function
int main()
{
struct Node *head = NULL;
struct Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
root->left->left->left = newNode(7);
root->left->left->right = newNode(8);
root->right->right->left = newNode(9);
root->right->right->right = newNode(10);
printf("Inorder Traversal of given Tree is:\n");
print(root);
root = extractLeafList(root, &head);
printf("\nExtracted Double Linked list is:\n");
printList(head);
printf("\nInorder traversal of modified tree is:\n");
print(root);
return 0;
}
Java
// Java program to extract leaf nodes from binary tree
// using double linked list
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
right = left = null;
}
}
public class BinaryTree
{
Node root;
Node head; // will point to head of DLL
Node prev; // temporary pointer
// The main function that links the list list to be traversed
public Node extractLeafList(Node root)
{
if (root == null)
return null;
if (root.left == null && root.right == null)
{
if (head == null)
{
head = root;
prev = root;
}
else
{
prev.right = root;
root.left = prev;
prev = root;
}
return null;
}
root.left = extractLeafList(root.left);
root.right = extractLeafList(root.right);
return root;
}
//Prints the DLL in both forward and reverse directions.
public void printDLL(Node head)
{
Node last = null;
while (head != null)
{
System.out.print(head.data + " ");
last = head;
head = head.right;
}
}
void inorder(Node node)
{
if (node == null)
return;
inorder(node.left);
System.out.print(node.data + " ");
inorder(node.right);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.right = new Node(6);
tree.root.left.left.left = new Node(7);
tree.root.left.left.right = new Node(8);
tree.root.right.right.left = new Node(9);
tree.root.right.right.right = new Node(10);
System.out.println("Inorder traversal of given tree is : ");
tree.inorder(tree.root);
tree.extractLeafList(tree.root);
System.out.println("");
System.out.println("Extracted double link list is : ");
tree.printDLL(tree.head);
System.out.println("");
System.out.println("Inorder traversal of modified tree is : ");
tree.inorder(tree.root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Python3
# Python program to extract leaf nodes from binary tree
# using double linked list
# A binary tree node
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = None
self.right = None
# Main function which extracts all leaves from given Binary Tree.
# The function returns new root of Binary Tree (Note that
# root may change if Binary Tree has only one node).
# The function also sets *head_ref as head of doubly linked list.
# left pointer of tree is used as prev in DLL
# and right pointer is used as next
def extractLeafList(root):
# Base Case
if root is None:
return None
if root.left is None and root.right is None:
# This node is going to be added to doubly linked
# list of leaves, set pointer of this node as
# previous head of DLL. We don't need to set left
# pointer as left is already None
root.right = extractLeafList.head
# Change the left pointer of previous head
if extractLeafList.head is not None:
extractLeafList.head.left = root
# Change head of linked list
extractLeafList.head = root
return None # Return new root
# Recur for right and left subtrees
root.right = extractLeafList(root.right)
root.left = extractLeafList(root.left)
return root
# Utility function for printing tree in InOrder
def printInorder(root):
if root is not None:
printInorder(root.left)
print (root.data,end=" ")
printInorder(root.right)
def printList(head):
while(head):
if head.data is not None:
print (head.data,end=" ")
head = head.right
# Driver program to test above function
extractLeafList.head = Node(None)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.right = Node(6)
root.left.left.left = Node(7)
root.left.left.right = Node(8)
root.right.right.left = Node(9)
root.right.right.right = Node(10)
print ("Inorder traversal of given tree is:")
printInorder(root)
root = extractLeafList(root)
print ("\nExtract Double Linked List is:")
printList(extractLeafList.head)
print ("\nInorder traversal of modified tree is:")
printInorder(root)
C#
// C# program to extract leaf
// nodes from binary tree
// using double linked list
using System;
// A binary tree node
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
right = left = null;
}
}
public class BinaryTree
{
Node root;
Node head; // will point to head of DLL
Node prev; // temporary pointer
// The main function that links
// the list list to be traversed
public Node extractLeafList(Node root)
{
if (root == null)
return null;
if (root.left == null && root.right == null)
{
if (head == null)
{
head = root;
prev = root;
}
else
{
prev.right = root;
root.left = prev;
prev = root;
}
return null;
}
root.left = extractLeafList(root.left);
root.right = extractLeafList(root.right);
return root;
}
// Prints the DLL in both forward
// and reverse directions.
public void printDLL(Node head)
{
Node last = null;
while (head != null)
{
Console.Write(head.data + " ");
last = head;
head = head.right;
}
}
void inorder(Node node)
{
if (node == null)
return;
inorder(node.left);
Console.Write(node.data + " ");
inorder(node.right);
}
// Driver code
public static void Main(String []args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
tree.root.right.right = new Node(6);
tree.root.left.left.left = new Node(7);
tree.root.left.left.right = new Node(8);
tree.root.right.right.left = new Node(9);
tree.root.right.right.right = new Node(10);
Console.WriteLine("Inorder traversal of given tree is : ");
tree.inorder(tree.root);
tree.extractLeafList(tree.root);
Console.WriteLine("");
Console.WriteLine("Extracted double link list is : ");
tree.printDLL(tree.head);
Console.WriteLine("");
Console.WriteLine("Inorder traversal of modified tree is : ");
tree.inorder(tree.root);
}
}
// This code has been contributed by 29AjayKumar
JavaScript
<script>
// javascript program to extract leaf nodes from binary tree
// using var linked list
// A binary tree node
class Node {
constructor(val) {
this.data = val;
this.left = null;
this.right = null;
}
}
var root;
var head; // will point to head of DLL
var prev; // temporary pointer
// The main function that links the list list to be traversed
function extractLeafList(root) {
if (root == null)
return null;
if (root.left == null && root.right == null) {
if (head == null) {
head = root;
prev = root;
}
else {
prev.right = root;
root.left = prev;
prev = root;
}
return null;
}
root.left = extractLeafList(root.left);
root.right = extractLeafList(root.right);
return root;
}
// Prints the DLL in both forward and reverse directions.
function printDLL(head) {
var last = null;
while (head != null) {
document.write(head.data + " ");
last = head;
head = head.right;
}
}
function inorder(node) {
if (node == null)
return;
inorder(node.left);
document.write(node.data + " ");
inorder(node.right);
}
// Driver program to test above functions
root = new Node(1);
root.left = new Node(2);
root.right = new Node(3);
root.left.left = new Node(4);
root.left.right = new Node(5);
root.right.right = new Node(6);
root.left.left.left = new Node(7);
root.left.left.right = new Node(8);
root.right.right.left = new Node(9);
root.right.right.right = new Node(10);
document.write("Inorder traversal of given tree is :<br/> ");
inorder(root);
extractLeafList(root);
document.write("<br/>");
document.write("Extracted var link list is :<br/> ");
printDLL(head);
document.write("<br/>");
document.write("Inorder traversal of modified tree is : <br/>");
inorder(root);
// This code contributed by umadevi9616
</script>
OutputInorder Traversal 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 a given Binary Tree.
Auxiliary Space: O(h), height of the Binary Tree due to recursion call stack.
Extract Leaves of a Binary Tree in a Doubly Linked List
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem