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

LeetCode 2583: Kth Largest Sum in a Binary Tree – Solution Explained

When working with binary trees, one common task is to analyze the properties of the tree's levels. In this blog post, we'll walk through a solution to LeetCode Problem 2583: Kth Largest Sum in a Binary Tree , a problem that challenges us to compute and find specific sums from different levels of a binary tree. Problem Statement You are given the root of a binary tree and a positive integer k . Your goal is to return the k-th largest level sum in the tree. The level sum is defined as the sum of the values of all nodes at the same depth in the tree. If the number of levels in the tree is less than k , the function should return -1 . Example 1: Input: root = [5, 8, 9, 2, 1, 3, 7, 4, 6] , k = 2 Output: 13 Explanation: Level 1 sum: 5 Level 2 sum: 8 + 9 = 17 Level 3 sum: 2 + 1 + 3 + 7 = 13 Level 4 sum: 4 + 6 = 10 The 2nd largest sum is 13 . Example 2: Input: root = [1, 2, null, 3] , k = 1 Output: 3 Explanation: The largest level sum is 3 (at the third level). This problem essentia

BCA 5th and 6th Semester Project | BCSP-064 | Synopsys and Project | Both | IGNOU BCA | 100% Accepted | July 2023 and Jan 2024

 Synopsys and Project | Both | July 2023 and Jan 2024 Title of the Project : - PRODUCT HUB Buy it from here (Synopsis + Project) : Synopsis Content :- Synopsis : An overview of the entire project, summarizing its main objectives, scope, and outcomes. Introduction : Introduce the project and provide context for the reader by explaining the problem or need that the project aims to address. Aim and Objective : Clearly state the goals and objectives of the project, outlining what you intend to achieve through its completion. Project Category : Define the domain or category to which the project belongs, helping readers understand the context and purpose of the project. Tools and Platform : List the software tools, programming languages, and platforms you'll be using to develop and implement the project. System Analysis : Discuss the preliminary analysis phase of the project, where you identify requirements,

MCS-021 | Data and File Structures | IGNOU BCA Solved Assignment | July 2021 & January 2022

  Course Code :- MCS-021 Course Title :- Data and File Structures Assignment Number :- BCA(3)/021/Assignment/2021-22 Maximum Marks :-  100 Weightage :-   25% Last Dates for Submission :- 31st October, 2021 (For July Session) &  15th April, 2022 (For January Session)  This assignment has four questions which carry 80 marks. Answer all the questions. Each question carries 20 marks. You may use illustrations and diagrams to enhance the explanations. Please go through the guidelines regarding assignments given in the Programme Guide. All the implementations should be in C programming language. Question 1: Write an algorithm that accepts a Binary Tree as inputs and outputs the traversals of Inorder , Postorder and Preorder of it. Question 2: Is it possible to implement multiple queues in a Stack. Justify your answer.  Question 3: List the names of all Sorting Algorithms along with their Complexities (Best case, Average case and Worst case). List as many names as possible along