返回

LeetCode - 114. Flatten Binary Tree to Linked List (Top 100)

IOS

Introduction

A binary tree is a data structure consisting of nodes, where each node has at most two child nodes, typically referred to as the left child and the right child. In a binary tree, the relationships between nodes are hierarchical, forming a tree-like structure.

On the other hand, a linked list is a linear data structure composed of nodes, where each node contains a value and a reference to the next node in the sequence. Linked lists are particularly useful for representing sequences of data, as they provide efficient insertion and deletion operations.

Problem Statement

The problem of flattening a binary tree into a linked list involves transforming a binary tree into a linked list while preserving the order of the elements. The resulting linked list should maintain the same sequence of elements as the original binary tree.

Solution Approach

The problem of flattening a binary tree into a linked list can be effectively solved using a recursive approach. The idea is to traverse the binary tree in a specific order and construct the linked list incrementally as we traverse. Here are the steps involved in the recursive solution:

  1. Base Case: If the current node is null, we simply return.

  2. Recursion: We recursively call the function on the left and right subtrees of the current node.

  3. Flattening: After the recursive calls return, we need to connect the current node to its right subtree. To do this, we make the left child of the current node point to the right child, and we set the right child of the current node to null.

  4. Return: Finally, we return the current node, which is now the root of the flattened linked list.

Implementation

Here is a possible Python implementation of the recursive solution:

def flatten_binary_tree(root):
    if root is None:
        return

    # Recursively flatten the left and right subtrees
    flatten_binary_tree(root.left)
    flatten_binary_tree(root.right)

    # Make the left child point to the right child
    root.left = root.right

    # Set the right child to null
    root.right = None

    # Return the current node
    return root

Complexity Analysis

The time complexity of the recursive solution is O(n), where n is the number of nodes in the binary tree. This is because we visit each node in the tree exactly once.

The space complexity of the recursive solution is O(n), as we need to store the recursive call stack.

Conclusion

The problem of flattening a binary tree into a linked list is a fundamental algorithmic problem that tests your understanding of data structures and recursion. The recursive solution presented in this post provides a concise and efficient way to solve the problem. By studying this solution, you can enhance your problem-solving abilities and deepen your understanding of algorithmic techniques.