Skip to main content

Converting a Binary Tree to a Doubly Linked List

When it comes to data structures in computer science, binary trees and linked lists are fundamental concepts that often come into play. In this post, we will explore an intriguing problem: converting a binary tree into a doubly linked list (DLL). This task may seem daunting, but with the right approach, we can achieve it seamlessly. Let's dive into the details!


Understanding the Problem

What is a Binary Tree?

A binary tree is a hierarchical structure in which each node has at most two children referred to as the left child and the right child. This structure is crucial for organizing data hierarchically, facilitating efficient searching, inserting, and deleting operations.

What is a Doubly Linked List?

A doubly linked list (DLL) is a linear data structure consisting of nodes, where each node contains three components: a data field and two pointers. One pointer points to the next node in the sequence (next), while the other points to the previous node (prev). This bidirectional nature of DLLs allows for easy traversal in both directions.

Our goal is to convert a given binary tree into a DLL such that:

  • The left and right pointers of the binary tree nodes are repurposed to act as the previous and next pointers in the DLL.
  • The order of nodes in the DLL reflects the in-order traversal of the binary tree.
  • The head of the DLL is the leftmost node of the binary tree.

Efficient Approach

To convert a binary tree into a DLL, we can use a recursive approach. Here’s how the process works:

  1. In-Order Traversal: The in-order traversal visits nodes in the order of left child, current node, and right child. This order is essential because it aligns with our requirement for the doubly linked list.

  2. Node Manipulation: During the traversal, we need to adjust the pointers of the nodes to link them as a doubly linked list.

Implementation

Below is a C++ implementation of the approach discussed:

class Node {
public:
    int data;
    Node* left;  // used as previous pointer in DLL
    Node* right; // used as next pointer in DLL
   
    Node(int val) : data(val), left(nullptr), right(nullptr) {}
};

class Solution {
public:
    void create(Node* root, Node* &head) {
        if (!root) return;

        // Traverse right first
        create(root->right, head);

        // Link current node with the head
        root->right = head; // Set the right pointer (next)
        if (head) {
            head->left = root; // Set the left pointer (previous)
        }
        head = root; // Move head to the current node

        // Traverse left
        create(root->left, head);
    }

    Node* bToDLL(Node* root) {
        Node* head = nullptr;
        create(root, head);
        return head; // Return the head of the doubly linked list
    }
};

 

Explanation of the Code

  1. Node Structure: We define a Node class to represent each node in the binary tree, with data, left, and right pointers.

  2. Recursive Function: The create function recursively processes the binary tree. It first traverses the right subtree, then links the current node to the head of the DLL, and finally traverses the left subtree.

  3. Main Function: The bToDLL function initializes the head pointer to nullptr and starts the conversion process.

Complexity Analysis

  • Time Complexity: The time complexity for this conversion is O(n), where n is the number of nodes in the binary tree. Each node is processed once during the traversal.

  • Space Complexity: The space complexity is O(h), where h is the height of the binary tree, due to the recursion stack. In the worst case, for a skewed tree, this can be O(n).

Converting a binary tree to a doubly linked list is a fascinating problem that showcases the power of recursion and pointer manipulation. By following the in-order traversal and appropriately adjusting node pointers, we can efficiently transform the binary tree structure into a DLL.

This approach not only enhances our understanding of trees and linked lists but also equips us with techniques that can be applied to various other data structure problems. Whether you're preparing for coding interviews or just looking to deepen your understanding of data structures, mastering this conversion process is a valuable skill.

Popular posts from this blog

Top 10 Beginner-Friendly LeetCode Questions and Their Solutions

If you're new to solving coding problems on LeetCode, it can feel overwhelming. Where do you start? Which problems are suitable for beginners? Don’t worry! In this blog post, I’ll guide you through 10 beginner-friendly LeetCode questions that are perfect for getting started on your coding journey. These problems will help you build confidence, improve your problem-solving skills, and lay a solid foundation in data structures and algorithms. Why Start with Beginner-Friendly Problems? Before diving into advanced topics like dynamic programming or graph theory, it’s essential to: Build a strong foundation in basic programming concepts. Understand how to approach a coding problem methodically. Gain familiarity with LeetCode’s platform and its problem structure. The following problems are simple yet impactful, designed to introduce you to common techniques like loops, arrays, strings, and basic math operations. 10 Beginner-Friendly LeetCode Problems 1. Two Sum (Easy) Problem Link : Two...

How to Solve LeetCode’s Hard Problems Without Getting Stuck

LeetCode’s hard problems can seem daunting, especially when you’re just getting comfortable with coding. Tackling these problems isn’t about innate talent—it’s about persistence, learning, and applying the right strategies. In this blog, I’ll share actionable tips and techniques to help you solve LeetCode hard problems without getting stuck and make consistent progress in your problem-solving journey. Why Are Hard Problems Hard? LeetCode hard problems challenge your understanding of advanced data structures, algorithms, and optimization techniques. Here’s why they’re tough: They require deep problem-solving skills and out-of-the-box thinking. Many involve multiple layers of complexity . Edge cases and large inputs often test your algorithm’s efficiency. They push you to master topics like dynamic programming, graph traversal, and segment trees. However, with the right approach, you can break down even the most complex problems into manageable parts. Start with the Right Mindset Appro...

Efficient Solution to LeetCode 2563: Count the Number of Fair Pairs in C++

 his problem tests our understanding of efficient array traversal techniques and highlights the power of binary search when working with sorted arrays. By the end of this post, you’ll have a clear, optimized solution in C++ that avoids Time Limit Exceeded (TLE) errors and uses two-pointer and binary search techniques . Let’s get started by breaking down the problem and exploring a step-by-step approach to a performant solution. Problem Statement Given: An integer array nums of size n . Two integers, lower and upper . Our goal is to count all pairs (i, j) where: 0 <= i < j < n , and lower <= nums[i] + nums[j] <= upper . Example Walkthrough Let's clarify with an example: Example 1 Input: nums = [0, 1, 7, 4, 4, 5] , lower = 3 , upper = 6 Output: 6 Explanation: Valid pairs that satisfy the condition are (0,3) , (0,4) , (0,5) , (1,3) , (1,4) , and (1,5) . Example 2 Input: nums = [1, 7, 9, 2, 5] , lower = 11 , upper = 11 Output: 1 Explanation: There is only one valid p...