Extract Leaves of a Binary Tree in a Doubly Linked List

Last Updated : 8 Sep, 2026

Given a Binary Tree, extract all its leaf nodes from left to right and form a Doubly Linked List (DLL) using the extracted nodes.

Remove the extracted leaf nodes from the original tree while preserving the structure of the remaining tree. Use the left and right pointers of each leaf node as the prev and next pointers of the DLL, respectively.

Note: The output contains the inorder traversal of the modified tree, followed by the DLL traversed from left to right and right to left.

Examples:

Input: root[] = [1, 2, 3, 4, 5, 6, 7]

binary_search_tree_21

Output:

Modified Tree : 2 1 3

binary_search_tree_20


Doubly Linked List : 4 <-> 5 <-> 6 <-> 7

binary_search_tree_19


Explanation: The leaf nodes are modified to form the DLL in-place. Thus their links are removed from the tree.

Input: root[] = [1, 2, 3, 4, 5]

binary_search_tree_18

Output:
Modified Tree : 2 1

binary_search_tree_17

Doubly Linked List: 4 <-> 5 <-> 3

binary_search_tree_22

Explanation: The leaf nodes 4, 5, 3 are removed from the tree and linked together to form the DLL from left to right.

Try It Yourself
redirect icon

[Naive Approach] Collect Leaves, Then Remove - O(n) Time and O(n) Auxiliary Space

The idea is to first collect all leaf nodes, remove them from the tree, and then connect them to form the Doubly Linked List (DLL).

  • Traverse the tree from left to right and store all leaf nodes in a list.
  • Traverse the tree again and remove each leaf by setting the corresponding pointer of its parent to null.
  • Connect the stored leaf nodes in their collected order using their left and right pointers as prev and next, respectively.
  • Return the first leaf as the head of the DLL.

Since the leaves are collected from left to right, they are already in the required order for the DLL.

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

vector<Node*> leaves;

// Store all leaf nodes from left to right.
void collectLeaves(Node* node) {
    if (node == nullptr)
        return;

    if (node->left == nullptr && node->right == nullptr) {
        leaves.push_back(node);
        return;
    }

    collectLeaves(node->left);
    collectLeaves(node->right);
}

// Remove leaf nodes from the tree.
void removeLeaves(Node* node) {
    if (node == nullptr)
        return;

    if (node->left != nullptr) {
        if (node->left->left == nullptr &&
            node->left->right == nullptr) {
            node->left = nullptr;
        } else {
            removeLeaves(node->left);
        }
    }

    if (node->right != nullptr) {
        if (node->right->left == nullptr &&
            node->right->right == nullptr) {
            node->right = nullptr;
        } else {
            removeLeaves(node->right);
        }
    }
}

// Convert leaf nodes into a Doubly Linked List.
Node* convertToDLL(Node* root) {
    if (root == nullptr)
        return nullptr;

    if (root->left == nullptr && root->right == nullptr)
        return root;

    leaves.clear();

    // Collect all leaf nodes.
    collectLeaves(root);

    // Remove leaf nodes from the tree.
    removeLeaves(root);

    // Connect the leaf nodes to form the DLL.
    for (int i = 0; i < leaves.size(); i++) {
        leaves[i]->left = (i > 0) ? leaves[i - 1] : nullptr;
        leaves[i]->right =
            (i + 1 < leaves.size()) ? leaves[i + 1] : nullptr;
    }

    return leaves[0];
}

// Print the modified tree in inorder.
void inorder(Node* root) {
    if (root == nullptr)
        return;

    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

// Print DLL from left to right and right to left.
void printDLL(Node* head) {
    Node* tail = nullptr;

    cout << "DLL (Left to Right): ";

    Node* curr = head;
    while (curr != nullptr) {
        cout << curr->data << " ";
        tail = curr;
        curr = curr->right;
    }

    cout << "\n";

    cout << "DLL (Right to Left): ";

    curr = tail;
    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->left;
    }

    cout << "\n";
}

int main() {
    /*
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    */

    Node* 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->left = new Node(6);
    root->right->right = new Node(7);

    Node* head = convertToDLL(root);

    cout << "Modified Tree (Inorder): ";
    inorder(root);
    cout << "\n";

    printDLL(head);

    return 0;
}
Java
import java.util.ArrayList;

class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {
    static ArrayList<Node> leaves = new ArrayList<>();

    // Store all leaf nodes from left to right.
    static void collectLeaves(Node node) {
        if (node == null)
            return;

        if (node.left == null && node.right == null) {
            leaves.add(node);
            return;
        }

        collectLeaves(node.left);
        collectLeaves(node.right);
    }

    // Remove leaf nodes from the tree.
    static void removeLeaves(Node node) {
        if (node == null)
            return;

        if (node.left != null) {
            if (node.left.left == null &&
                node.left.right == null) {
                node.left = null;
            } else {
                removeLeaves(node.left);
            }
        }

        if (node.right != null) {
            if (node.right.left == null &&
                node.right.right == null) {
                node.right = null;
            } else {
                removeLeaves(node.right);
            }
        }
    }

    // Convert leaf nodes into a Doubly Linked List.
    static Node convertToDLL(Node root) {
        if (root == null)
            return null;

        if (root.left == null && root.right == null)
            return root;

        leaves.clear();

        // Collect all leaf nodes.
        collectLeaves(root);

        // Remove leaf nodes from the tree.
        removeLeaves(root);

        // Connect the leaf nodes to form the DLL.
        for (int i = 0; i < leaves.size(); i++) {
            leaves.get(i).left = (i > 0) ? leaves.get(i - 1) : null;
            leaves.get(i).right =
                (i + 1 < leaves.size()) ? leaves.get(i + 1) : null;
        }

        return leaves.get(0);
    }

    // Print the modified tree in inorder.
    static void inorder(Node root) {
        if (root == null)
            return;

        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }

    // Print DLL from left to right and right to left.
    static void printDLL(Node head) {
        Node tail = null;

        System.out.print("DLL (Left to Right): ");

        Node curr = head;
        while (curr != null) {
            System.out.print(curr.data + " ");
            tail = curr;
            curr = curr.right;
        }

        System.out.println();

        System.out.print("DLL (Right to Left): ");

        curr = tail;
        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.left;
        }

        System.out.println();
    }

    public static void main(String[] args) {
        /*
                  1
                /   \
               2     3
              / \   / \
             4   5 6   7
        */

        Node 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.left = new Node(6);
        root.right.right = new Node(7);

        Node head = convertToDLL(root);

        System.out.print("Modified Tree (Inorder): ");
        inorder(root);
        System.out.println();

        printDLL(head);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


# Store all leaf nodes from left to right.
def collectLeaves(node, leaves):
    if node is None:
        return

    if node.left is None and node.right is None:
        leaves.append(node)
        return

    collectLeaves(node.left, leaves)
    collectLeaves(node.right, leaves)


# Remove leaf nodes from the tree.
def removeLeaves(node):
    if node is None:
        return

    if node.left is not None:
        if node.left.left is None and node.left.right is None:
            node.left = None
        else:
            removeLeaves(node.left)

    if node.right is not None:
        if node.right.left is None and node.right.right is None:
            node.right = None
        else:
            removeLeaves(node.right)


# Convert leaf nodes into a Doubly Linked List.
def convertToDLL(root):
    if root is None:
        return None

    if root.left is None and root.right is None:
        return root

    leaves = []

    # Collect all leaf nodes.
    collectLeaves(root, leaves)

    # Remove leaf nodes from the tree.
    removeLeaves(root)

    # Connect the leaf nodes to form the DLL.
    for i in range(len(leaves)):
        leaves[i].left = leaves[i - 1] if i > 0 else None
        leaves[i].right = leaves[i + 1] if i + 1 < len(leaves) else None

    return leaves[0]


# Print the modified tree in inorder.
def inorder(root):
    if root is None:
        return

    inorder(root.left)
    print(root.data, end=" ")
    inorder(root.right)


# Print DLL from left to right and right to left.
def printDLL(head):
    tail = None

    print("DLL (Left to Right): ", end="")

    curr = head
    while curr is not None:
        print(curr.data, end=" ")
        tail = curr
        curr = curr.right

    print()

    print("DLL (Right to Left): ", end="")

    curr = tail
    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.left

    print()


if __name__ == "__main__":
    
    """
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    """

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.right.left = Node(6)
    root.right.right = Node(7)

    head = convertToDLL(root)

    print("Modified Tree (Inorder): ", end="")
    inorder(root)
    print()

    printDLL(head)
C#
using System;
using System.Collections.Generic;

class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class GFG
{
    static List<Node> leaves = new List<Node>();

    // Store all leaf nodes from left to right.
    static void collectLeaves(Node node)
    {
        if (node == null)
            return;

        if (node.left == null && node.right == null)
        {
            leaves.Add(node);
            return;
        }

        collectLeaves(node.left);
        collectLeaves(node.right);
    }

    // Remove leaf nodes from the tree.
    static void removeLeaves(Node node)
    {
        if (node == null)
            return;

        if (node.left != null)
        {
            if (node.left.left == null &&
                node.left.right == null)
            {
                node.left = null;
            }
            else
            {
                removeLeaves(node.left);
            }
        }

        if (node.right != null)
        {
            if (node.right.left == null &&
                node.right.right == null)
            {
                node.right = null;
            }
            else
            {
                removeLeaves(node.right);
            }
        }
    }

    // Convert leaf nodes into a Doubly Linked List.
    static Node convertToDLL(Node root)
    {
        if (root == null)
            return null;

        if (root.left == null && root.right == null)
            return root;

        leaves.Clear();

        // Collect all leaf nodes.
        collectLeaves(root);

        // Remove leaf nodes from the tree.
        removeLeaves(root);

        // Connect the leaf nodes to form the DLL.
        for (int i = 0; i < leaves.Count; i++)
        {
            leaves[i].left = i > 0 ? leaves[i - 1] : null;
            leaves[i].right =
                i + 1 < leaves.Count ? leaves[i + 1] : null;
        }

        return leaves[0];
    }

    // Print the modified tree in inorder.
    static void inorder(Node root)
    {
        if (root == null)
            return;

        inorder(root.left);
        Console.Write(root.data + " ");
        inorder(root.right);
    }

    // Print DLL from left to right and right to left.
    static void printDLL(Node head)
    {
        Node tail = null;

        Console.Write("DLL (Left to Right): ");

        Node curr = head;
        while (curr != null)
        {
            Console.Write(curr.data + " ");
            tail = curr;
            curr = curr.right;
        }

        Console.WriteLine();

        Console.Write("DLL (Right to Left): ");

        curr = tail;
        while (curr != null)
        {
            Console.Write(curr.data + " ");
            curr = curr.left;
        }

        Console.WriteLine();
    }

    static void Main()
    {
        /*
                  1
                /   \
               2     3
              / \   / \
             4   5 6   7
        */

        Node 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.left = new Node(6);
        root.right.right = new Node(7);

        Node head = convertToDLL(root);

        Console.Write("Modified Tree (Inorder): ");
        inorder(root);
        Console.WriteLine();

        printDLL(head);
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}


// Store all leaf nodes from left to right.
function collectLeaves(node, leaves) {
    if (node === null)
        return;

    if (node.left === null && node.right === null) {
        leaves.push(node);
        return;
    }

    collectLeaves(node.left, leaves);
    collectLeaves(node.right, leaves);
}


// Remove leaf nodes from the tree.
function removeLeaves(node) {
    if (node === null)
        return;

    if (node.left !== null) {
        if (node.left.left === null &&
            node.left.right === null) {
            node.left = null;
        } else {
            removeLeaves(node.left);
        }
    }

    if (node.right !== null) {
        if (node.right.left === null &&
            node.right.right === null) {
            node.right = null;
        } else {
            removeLeaves(node.right);
        }
    }
}


// Convert leaf nodes into a Doubly Linked List.
function convertToDLL(root) {
    if (root === null)
        return null;

    if (root.left === null && root.right === null)
        return root;

    let leaves = [];

    // Collect all leaf nodes.
    collectLeaves(root, leaves);

    // Remove leaf nodes from the tree.
    removeLeaves(root);

    // Connect the leaf nodes to form the DLL.
    for (let i = 0; i < leaves.length; i++) {
        leaves[i].left = i > 0 ? leaves[i - 1] : null;
        leaves[i].right =
            i + 1 < leaves.length ? leaves[i + 1] : null;
    }

    return leaves[0];
}


// Print the modified tree in inorder.
function inorder(root) {
    if (root === null)
        return;

    inorder(root.left);
    process.stdout.write(root.data + " ");
    inorder(root.right);
}


// Print DLL from left to right and right to left.
function printDLL(head) {
    let tail = null;

    process.stdout.write("DLL (Left to Right): ");

    let curr = head;
    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        tail = curr;
        curr = curr.right;
    }

    console.log();

    process.stdout.write("DLL (Right to Left): ");

    curr = tail;
    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        curr = curr.left;
    }

    console.log();
}


/*
          1
        /   \
       2     3
      / \   / \
     4   5 6   7
*/

let 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.left = new Node(6);
root.right.right = new Node(7);

let head = convertToDLL(root);

process.stdout.write("Modified Tree (Inorder): ");
inorder(root);
console.log();

printDLL(head);

Output
Modified Tree (Inorder): 2 1 3 
DLL (Left to Right): 4 5 6 7 
DLL (Right to Left): 7 6 5 4 

[Better Approach] Recursion with Parent Tracking - O(n) Time and O(h) Auxiliary Space

Instead of storing the leaf nodes separately, process each leaf as soon as it is encountered.

The recursive function keeps track of the parent node and whether the current node is its left or right child. This allows the leaf to be removed immediately while it is added to the DLL.

  • Initialize head and tail as null.
  • Traverse the tree from left to right while keeping track of the parent.
  • If the current node is a leaf, detach it from its parent and add it to the DLL.
  • Otherwise, recursively process its left and right subtrees.
  • Return head as the head of the DLL.

Since the tree is traversed from left to right, the leaf nodes are added to the DLL in the same order.

Consider the following Binary Tree:

binary_search_tree_21

Initially: head = nullptr, tail = nullptr

The traversal starts from the root and moves from left to right.

  • Node 1 is not a leaf, so recursively process its left subtree.
  • Node 2 is not a leaf, so process its left child.
  • Visit 4: It is a leaf. Detach it from 2 and add it to the DLL.
  • 4
  • Visit 5: Detach it from 2 and connect it after 4.
  • 4 <-> 5
  • Visit 6: Detach it from 3 and connect it after 5.
  • 4 <-> 5 <-> 6
  • Visit 7: Detach it from 3 and connect it after 6.
  • 4 <-> 5 <-> 6 <-> 7

After the traversal, the modified tree is:

binary_search_tree_20

And the final DLL is: 4 <-> 5 <-> 6 <-> 7

binary_search_tree_19

Thus, each original leaf is removed from the tree and added to the DLL in left-to-right order.

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

Node* head = nullptr;
Node* tail = nullptr;

// Convert leaf nodes into a Doubly Linked List.
void convertToDLLUtil(Node* node, Node* parent, bool isLeftChild) {
    if (node == nullptr)
        return;

    // If the node is a leaf, remove it and add it to the DLL.
    if (node->left == nullptr && node->right == nullptr) {
        if (parent != nullptr) {
            if (isLeftChild)
                parent->left = nullptr;
            else
                parent->right = nullptr;
        }

        // Add the leaf to the DLL.
        if (head == nullptr) {
            head = node;
        } else {
            tail->right = node;
            node->left = tail;
        }

        tail = node;
        return;
    }

    convertToDLLUtil(node->left, node, true);
    convertToDLLUtil(node->right, node, false);
}

// Convert all leaf nodes of the tree into a DLL.
Node* convertToDLL(Node* root) {
    if (root == nullptr)
        return nullptr;

    if (root->left == nullptr && root->right == nullptr)
        return root;

    head = nullptr;
    tail = nullptr;

    convertToDLLUtil(root, nullptr, false);

    return head;
}

// Print the modified tree in inorder.
void inorder(Node* root) {
    if (root == nullptr)
        return;

    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

// Print DLL from left to right and right to left.
void printDLL(Node* head) {
    Node* curr = head;
    Node* tail = nullptr;

    cout << "DLL (Left to Right): ";

    while (curr != nullptr) {
        cout << curr->data << " ";
        tail = curr;
        curr = curr->right;
    }

    cout << "\n";

    cout << "DLL (Right to Left): ";

    curr = tail;

    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->left;
    }

    cout << "\n";
}

int main() {
    /*
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    */

    Node* 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->left = new Node(6);
    root->right->right = new Node(7);

    Node* head = convertToDLL(root);

    cout << "Modified Tree (Inorder): ";
    inorder(root);
    cout << "\n";

    printDLL(head);

    return 0;
}
Java
class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

class GFG {

    static Node head = null;
    static Node tail = null;

    // Convert leaf nodes into a Doubly Linked List.
    static void convertToDLLUtil(Node node, Node parent, boolean isLeftChild) {
        if (node == null)
            return;

        // If the node is a leaf, remove it and add it to the DLL.
        if (node.left == null && node.right == null) {
            if (parent != null) {
                if (isLeftChild)
                    parent.left = null;
                else
                    parent.right = null;
            }

            // Add the leaf to the DLL.
            if (head == null) {
                head = node;
            } else {
                tail.right = node;
                node.left = tail;
            }

            tail = node;
            return;
        }

        convertToDLLUtil(node.left, node, true);
        convertToDLLUtil(node.right, node, false);
    }

    // Convert all leaf nodes of the tree into a DLL.
    static Node convertToDLL(Node root) {
        if (root == null)
            return null;

        if (root.left == null && root.right == null)
            return root;

        head = null;
        tail = null;

        convertToDLLUtil(root, null, false);

        return head;
    }

    // Print the modified tree in inorder.
    static void inorder(Node root) {
        if (root == null)
            return;

        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }

    // Print DLL from left to right and right to left.
    static void printDLL(Node head) {
        Node curr = head;
        Node tail = null;

        System.out.print("DLL (Left to Right): ");

        while (curr != null) {
            System.out.print(curr.data + " ");
            tail = curr;
            curr = curr.right;
        }

        System.out.println();

        System.out.print("DLL (Right to Left): ");

        curr = tail;

        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.left;
        }

        System.out.println();
    }

    public static void main(String[] args) {
        /*
                  1
                /   \
               2     3
              / \   / \
             4   5 6   7
        */

        Node 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.left = new Node(6);
        root.right.right = new Node(7);

        Node head = convertToDLL(root);

        System.out.print("Modified Tree (Inorder): ");
        inorder(root);
        System.out.println();

        printDLL(head);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


head = None
tail = None


# Convert leaf nodes into a Doubly Linked List.
def convertToDLLUtil(node, parent, isLeftChild):
    global head, tail

    if node is None:
        return

    # If the node is a leaf, remove it and add it to the DLL.
    if node.left is None and node.right is None:
        if parent is not None:
            if isLeftChild:
                parent.left = None
            else:
                parent.right = None

        # Add the leaf to the DLL.
        if head is None:
            head = node
        else:
            tail.right = node
            node.left = tail

        tail = node
        return

    convertToDLLUtil(node.left, node, True)
    convertToDLLUtil(node.right, node, False)


# Convert all leaf nodes of the tree into a DLL.
def convertToDLL(root):
    global head, tail

    if root is None:
        return None

    if root.left is None and root.right is None:
        return root

    head = None
    tail = None

    convertToDLLUtil(root, None, False)

    return head


# Print the modified tree in inorder.
def inorder(root):
    if root is None:
        return

    inorder(root.left)
    print(root.data, end=" ")
    inorder(root.right)


# Print DLL from left to right and right to left.
def printDLL(head):
    curr = head
    tail = None

    print("DLL (Left to Right): ", end="")

    while curr is not None:
        print(curr.data, end=" ")
        tail = curr
        curr = curr.right

    print()

    print("DLL (Right to Left): ", end="")

    curr = tail

    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.left

    print()


if __name__ == "__main__":
    
    """
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    """

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.right.left = Node(6)
    root.right.right = Node(7)

    head = convertToDLL(root)

    print("Modified Tree (Inorder): ", end="")
    inorder(root)
    print()

    printDLL(head)
C#
using System;

class Node
{
    public int data;
    public Node left;
    public Node right;

    public Node(int x)
    {
        data = x;
        left = right = null;
    }
}

class GFG
{
    static Node head = null;
    static Node tail = null;

    // Convert leaf nodes into a Doubly Linked List.
    static void convertToDLLUtil(Node node, Node parent, bool isLeftChild)
    {
        if (node == null)
            return;

        // If the node is a leaf, remove it and add it to the DLL.
        if (node.left == null && node.right == null)
        {
            if (parent != null)
            {
                if (isLeftChild)
                    parent.left = null;
                else
                    parent.right = null;
            }

            // Add the leaf to the DLL.
            if (head == null)
            {
                head = node;
            }
            else
            {
                tail.right = node;
                node.left = tail;
            }

            tail = node;
            return;
        }

        convertToDLLUtil(node.left, node, true);
        convertToDLLUtil(node.right, node, false);
    }

    // Convert all leaf nodes of the tree into a DLL.
    static Node convertToDLL(Node root)
    {
        if (root == null)
            return null;

        if (root.left == null && root.right == null)
            return root;

        head = null;
        tail = null;

        convertToDLLUtil(root, null, false);

        return head;
    }

    // Print the modified tree in inorder.
    static void inorder(Node root)
    {
        if (root == null)
            return;

        inorder(root.left);
        Console.Write(root.data + " ");
        inorder(root.right);
    }

    // Print DLL from left to right and right to left.
    static void printDLL(Node head)
    {
        Node curr = head;
        Node tail = null;

        Console.Write("DLL (Left to Right): ");

        while (curr != null)
        {
            Console.Write(curr.data + " ");
            tail = curr;
            curr = curr.right;
        }

        Console.WriteLine();

        Console.Write("DLL (Right to Left): ");

        curr = tail;

        while (curr != null)
        {
            Console.Write(curr.data + " ");
            curr = curr.left;
        }

        Console.WriteLine();
    }

    static void Main()
    {
        /*
                  1
                /   \
               2     3
              / \   / \
             4   5 6   7
        */

        Node 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.left = new Node(6);
        root.right.right = new Node(7);

        Node head = convertToDLL(root);

        Console.Write("Modified Tree (Inorder): ");
        inorder(root);
        Console.WriteLine();

        printDLL(head);
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}


// Convert leaf nodes into a Doubly Linked List.
function convertToDLLUtil(node, parent, isLeftChild, list) {
    if (node === null)
        return;

    // If the node is a leaf, remove it and add it to the DLL.
    if (node.left === null && node.right === null) {
        if (parent !== null) {
            if (isLeftChild)
                parent.left = null;
            else
                parent.right = null;
        }

        // Add the leaf to the DLL.
        if (list.head === null) {
            list.head = node;
        } else {
            list.tail.right = node;
            node.left = list.tail;
        }

        list.tail = node;
        return;
    }

    convertToDLLUtil(node.left, node, true, list);
    convertToDLLUtil(node.right, node, false, list);
}


// Convert all leaf nodes of the tree into a DLL.
function convertToDLL(root) {
    if (root === null)
        return null;

    if (root.left === null && root.right === null)
        return root;

    let list = {
        head: null,
        tail: null
    };

    convertToDLLUtil(root, null, false, list);

    return list.head;
}


// Print the modified tree in inorder.
function inorder(root) {
    if (root === null)
        return;

    inorder(root.left);
    process.stdout.write(root.data + " ");
    inorder(root.right);
}


// Print DLL from left to right and right to left.
function printDLL(head) {
    let curr = head;
    let tail = null;

    process.stdout.write("DLL (Left to Right): ");

    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        tail = curr;
        curr = curr.right;
    }

    console.log();

    process.stdout.write("DLL (Right to Left): ");

    curr = tail;

    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        curr = curr.left;
    }

    console.log();
}


// Driver code

    /*
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    */

    let 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.left = new Node(6);
    root.right.right = new Node(7);

    let head = convertToDLL(root);

    process.stdout.write("Modified Tree (Inorder): ");
    inorder(root);
    console.log();

    printDLL(head);

Output
Modified Tree (Inorder): 2 1 3 
DLL (Left to Right): 4 5 6 7 
DLL (Right to Left): 7 6 5 4 

[Expected Approach] Recursion with Modified Subtree - O(n) Time and O(h) Auxiliary Space

The idea is to let the recursive function return the modified subtree after processing it.

If the current node is a leaf, add it to the DLL and return nullptr. The parent then assigns this nullptr to its child pointer, automatically removing the leaf from the tree.

For a non-leaf node, recursively process both subtrees, update its child pointers, and return the current node.

Since the left subtree is processed before the right subtree, the DLL maintains the left-to-right order of the original leaf nodes.

Consider the following Binary Tree:

binary_search_tree_21

Initially, both head and tail are nullptr.

The tree is traversed from left to right. Whenever a leaf node is found, it is added to the DLL and nullptr is returned to its parent. This removes the leaf from the tree.

Visit 4:

  • It is a leaf, so add it to the DLL.
  • DLL: 4
  • Node 2 removes 4 from its left child.

Visit 5:

  • It is a leaf, so add it after 4.
  • DLL: 4 <-> 5
  • Node 2 removes 5 from its right child.

Visit 6:

  • It is a leaf, so add it after 5.
  • DLL: 4 <-> 5 <-> 6
  • Node 3 removes 6 from its left child.

Visit 7:

  • It is a leaf, so add it after 6.
  • DLL: 4 <-> 5 <-> 6 <-> 7
  • Node 3 removes 7 from its right child.

After processing all nodes, the remaining tree is:

binary_search_tree_20

The final DLL is: 4 <-> 5 <-> 6 <-> 7

binary_search_tree_19

Thus, all original leaf nodes are removed from the tree and connected into a DLL while preserving their left-to-right order.

C++
#include <bits/stdc++.h>
using namespace std;

class Node {
public:
    int data;
    Node* left;
    Node* right;

    Node(int x) {
        data = x;
        left = right = nullptr;
    }
};

Node* head = nullptr;
Node* tail = nullptr;

// Convert leaf nodes into a Doubly Linked List.
Node* convertToDLLUtil(Node* node) {
    if (node == nullptr)
        return nullptr;

    // If the node is a leaf, remove it and add it to the DLL.
    if (node->left == nullptr && node->right == nullptr) {

        // Add the leaf to the DLL.
        if (head == nullptr) {
            head = node;
        } else {
            tail->right = node;
            node->left = tail;
        }

        tail = node;

        return nullptr;
    }

    node->left = convertToDLLUtil(node->left);
    node->right = convertToDLLUtil(node->right);

    return node;
}

// Convert all leaf nodes of the tree into a DLL.
Node* convertToDLL(Node* root) {
    if (root == nullptr)
        return nullptr;

    head = nullptr;
    tail = nullptr;

    root = convertToDLLUtil(root);

    return head;
}

// Print the modified tree in inorder.
void inorder(Node* root) {
    if (root == nullptr)
        return;

    inorder(root->left);
    cout << root->data << " ";
    inorder(root->right);
}

// Print DLL from left to right and right to left.
void printDLL(Node* head) {
    Node* curr = head;
    Node* tail = nullptr;

    cout << "DLL (Left to Right): ";

    while (curr != nullptr) {
        cout << curr->data << " ";
        tail = curr;
        curr = curr->right;
    }

    cout << "\n";

    cout << "DLL (Right to Left): ";

    curr = tail;

    while (curr != nullptr) {
        cout << curr->data << " ";
        curr = curr->left;
    }

    cout << "\n";
}

int main() {
    /*
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    */

    Node* 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->left = new Node(6);
    root->right->right = new Node(7);

    Node* head = convertToDLL(root);

    cout << "Modified Tree (Inorder): ";
    inorder(root);
    cout << "\n";

    printDLL(head);

    return 0;
}
Java
class Node {
    int data;
    Node left;
    Node right;

    Node(int x) {
        data = x;
        left = right = null;
    }
}

public class GFG {

    static Node head = null;
    static Node tail = null;

    // Convert leaf nodes into a Doubly Linked List.
    static Node convertToDLLUtil(Node node) {
        if (node == null)
            return null;

        // If the node is a leaf, remove it and add it to the DLL.
        if (node.left == null && node.right == null) {

            // Add the leaf to the DLL.
            if (head == null) {
                head = node;
            } else {
                tail.right = node;
                node.left = tail;
            }

            tail = node;

            return null;
        }

        node.left = convertToDLLUtil(node.left);
        node.right = convertToDLLUtil(node.right);

        return node;
    }

    // Convert all leaf nodes of the tree into a DLL.
    static Node convertToDLL(Node root) {
        if (root == null)
            return null;

        head = null;
        tail = null;

        root = convertToDLLUtil(root);

        return head;
    }

    // Print the modified tree in inorder.
    static void inorder(Node root) {
        if (root == null)
            return;

        inorder(root.left);
        System.out.print(root.data + " ");
        inorder(root.right);
    }

    // Print DLL from left to right and right to left.
    static void printDLL(Node head) {
        Node curr = head;
        Node tail = null;

        System.out.print("DLL (Left to Right): ");

        while (curr != null) {
            System.out.print(curr.data + " ");
            tail = curr;
            curr = curr.right;
        }

        System.out.println();

        System.out.print("DLL (Right to Left): ");

        curr = tail;

        while (curr != null) {
            System.out.print(curr.data + " ");
            curr = curr.left;
        }

        System.out.println();
    }

    public static void main(String[] args) {
        /*
                  1
                /   \
               2     3
              / \   / \
             4   5 6   7
        */

        Node 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.left = new Node(6);
        root.right.right = new Node(7);

        Node head = convertToDLL(root);

        System.out.print("Modified Tree (Inorder): ");
        inorder(root);
        System.out.println();

        printDLL(head);
    }
}
Python
class Node:
    def __init__(self, x):
        self.data = x
        self.left = None
        self.right = None


head = None
tail = None


# Convert leaf nodes into a Doubly Linked List.
def convertToDLLUtil(node):
    global head, tail

    if node is None:
        return None

    # If the node is a leaf, remove it and add it to the DLL.
    if node.left is None and node.right is None:

        # Add the leaf to the DLL.
        if head is None:
            head = node
        else:
            tail.right = node
            node.left = tail

        tail = node

        return None

    node.left = convertToDLLUtil(node.left)
    node.right = convertToDLLUtil(node.right)

    return node


# Convert all leaf nodes of the tree into a DLL.
def convertToDLL(root):
    global head, tail

    if root is None:
        return None

    head = None
    tail = None

    root = convertToDLLUtil(root)

    return head


# Print the modified tree in inorder.
def inorder(root):
    if root is None:
        return

    inorder(root.left)
    print(root.data, end=" ")
    inorder(root.right)


# Print DLL from left to right and right to left.
def printDLL(head):
    curr = head
    tail = None

    print("DLL (Left to Right): ", end="")

    while curr is not None:
        print(curr.data, end=" ")
        tail = curr
        curr = curr.right

    print()

    print("DLL (Right to Left): ", end="")

    curr = tail

    while curr is not None:
        print(curr.data, end=" ")
        curr = curr.left

    print()


def main():
    """
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    """

    root = Node(1)
    root.left = Node(2)
    root.right = Node(3)

    root.left.left = Node(4)
    root.left.right = Node(5)

    root.right.left = Node(6)
    root.right.right = Node(7)

    head = convertToDLL(root)

    print("Modified Tree (Inorder): ", end="")
    inorder(root)
    print()

    printDLL(head)


if __name__ == "__main__":
    main()
C#
using System;

class Node {
    public int data;
    public Node left;
    public Node right;

    public Node(int x) {
        data = x;
        left = right = null;
    }
}

class Program {
    static Node head = null;
    static Node tail = null;

    // Convert leaf nodes into a Doubly Linked List.
    static Node convertToDLLUtil(Node node) {
        if (node == null)
            return null;

        // If the node is a leaf, remove it and add it to the DLL.
        if (node.left == null && node.right == null) {

            // Add the leaf to the DLL.
            if (head == null) {
                head = node;
            } else {
                tail.right = node;
                node.left = tail;
            }

            tail = node;

            return null;
        }

        node.left = convertToDLLUtil(node.left);
        node.right = convertToDLLUtil(node.right);

        return node;
    }

    // Convert all leaf nodes of the tree into a DLL.
    static Node convertToDLL(Node root) {
        if (root == null)
            return null;

        head = null;
        tail = null;

        root = convertToDLLUtil(root);

        return head;
    }

    // Print the modified tree in inorder.
    static void inorder(Node root) {
        if (root == null)
            return;

        inorder(root.left);
        Console.Write(root.data + " ");
        inorder(root.right);
    }

    // Print DLL from left to right and right to left.
    static void printDLL(Node head) {
        Node curr = head;
        Node tail = null;

        Console.Write("DLL (Left to Right): ");

        while (curr != null) {
            Console.Write(curr.data + " ");
            tail = curr;
            curr = curr.right;
        }

        Console.WriteLine();

        Console.Write("DLL (Right to Left): ");

        curr = tail;

        while (curr != null) {
            Console.Write(curr.data + " ");
            curr = curr.left;
        }

        Console.WriteLine();
    }

    static void Main() {
        /*
                  1
                /   \
               2     3
              / \   / \
             4   5 6   7
        */

        Node 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.left = new Node(6);
        root.right.right = new Node(7);

        Node head = convertToDLL(root);

        Console.Write("Modified Tree (Inorder): ");
        inorder(root);
        Console.WriteLine();

        printDLL(head);
    }
}
JavaScript
class Node {
    constructor(x) {
        this.data = x;
        this.left = null;
        this.right = null;
    }
}


// Convert leaf nodes into a Doubly Linked List.
function convertToDLLUtil(node, list) {
    if (node === null)
        return null;

    // If the node is a leaf, remove it and add it to the DLL.
    if (node.left === null && node.right === null) {

        // Add the leaf to the DLL.
        if (list.head === null) {
            list.head = node;
        } else {
            list.tail.right = node;
            node.left = list.tail;
        }

        list.tail = node;

        return null;
    }

    node.left = convertToDLLUtil(node.left, list);
    node.right = convertToDLLUtil(node.right, list);

    return node;
}


// Convert all leaf nodes of the tree into a DLL.
function convertToDLL(root) {
    if (root === null)
        return null;

    let list = {
        head: null,
        tail: null
    };

    root = convertToDLLUtil(root, list);

    return list.head;
}


// Print the modified tree in inorder.
function inorder(root) {
    if (root === null)
        return;

    inorder(root.left);
    process.stdout.write(root.data + " ");
    inorder(root.right);
}


// Print DLL from left to right and right to left.
function printDLL(head) {
    let curr = head;
    let tail = null;

    process.stdout.write("DLL (Left to Right): ");

    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        tail = curr;
        curr = curr.right;
    }

    console.log();

    process.stdout.write("DLL (Right to Left): ");

    curr = tail;

    while (curr !== null) {
        process.stdout.write(curr.data + " ");
        curr = curr.left;
    }

    console.log();
}


// Driver code

    /*
              1
            /   \
           2     3
          / \   / \
         4   5 6   7
    */

    let 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.left = new Node(6);
    root.right.right = new Node(7);

    let head = convertToDLL(root);

    process.stdout.write("Modified Tree (Inorder): ");
    inorder(root);
    console.log();

    printDLL(head);

Output
Modified Tree (Inorder): 2 1 3 
DLL (Left to Right): 4 5 6 7 
DLL (Right to Left): 7 6 5 4 
Comment