Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Flatten Binary Tree to Linked List

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "114" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.

Problem Statement

Given the root of a binary tree, flatten the tree into a "linked list": The "linked list" should use the same TreeNode class where the right child pointer points to the next node in the list and the left child pointer is always null. The "linked list" should be in the same order as a pre-order traversal of the binary tree. Example 1: Input: root = [1,2,5,3,4,null,6] Output: [1,null,2,null,3,null,4,null,5,null,6] Example 2: Input: root = [] Output: [] Example 3: Input: root = [0] Output: [0] Constraints: The number of nodes in the tree is in the range [0, 2000]. -100 <= Node.val <= 100 Follow up: Can you flatten the tree in-place (with O(1) extra space)?

Explanation

Here's the breakdown of the solution:

  • In-place Preorder Traversal and Restructuring: Perform a modified preorder traversal. During the traversal, we'll restructure the tree to form the linked list directly, without using extra space for storing nodes.
  • Maintain a Tail Pointer: Use a tail pointer to keep track of the last node in the flattened list. As we traverse, we attach the current node to the tail's right, and update the tail to be the current node.
  • Handle Left Subtree First: Process the left subtree, then the right. The left subtree's flattened linked list is attached between the current node and the original right subtree.

  • Time and Space Complexity: O(N) time complexity, where N is the number of nodes in the tree, and O(1) space complexity.

Code

    class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def flatten(root):
    """
    Flattens a binary tree in-place using preorder traversal.
    """
    def flatten_recursive(node):
        if not node:
            return None

        nonlocal tail

        # Store left and right children as they will be modified
        left_subtree = node.left
        right_subtree = node.right

        # Attach the current node to the tail
        tail.right = node
        tail.left = None  # Crucial: Set left to None as required
        tail = node

        # Flatten left subtree
        flatten_recursive(left_subtree)

        # Flatten right subtree
        flatten_recursive(right_subtree)

    # Initialize tail to a dummy node; the actual flattening starts from root
    dummy = TreeNode()
    tail = dummy
    flatten_recursive(root)

    # Adjust the root of the original tree to be the head of flattened linked list
    if dummy.right:
        root_val = dummy.right.val
        root.val = root_val

    # Handle edge cases of empty tree and single-node tree
    if not root or not root.left and not root.right:
        return

    # Adjust the original root node and its connections with dummy node
    if dummy.right:
        root.left = None  # Make sure the root's left child is None
        root.right = dummy.right.right

        current = root
        while current.right:
            current = current.right
        if dummy.right.right:

           dummy_curr = dummy.right.right

           while dummy_curr:
               current.right = dummy_curr

               if dummy_curr.right:
                   current = current.right
                   dummy_curr = dummy_curr.right
               else:
                   dummy_curr = None


        # Clean up dummy node pointer, after use.
        dummy.right = None

More from this blog

C

Chatmagic blog

2894 posts