LeetCode 114: Flatten Binary Tree to Linked List Solution

Master LeetCode problem 114 (Flatten Binary Tree to Linked List), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

114. Flatten Binary Tree to Linked List

Problem Explanation

Explanation

To flatten a binary tree into a linked list in pre-order traversal, we can follow these steps:

  1. Recursively flatten the left subtree and right subtree.
  2. Store the right subtree in a temporary variable.
  3. Make the left subtree as the right subtree.
  4. Traverse to the end of the new right subtree and attach the original right subtree.

Time Complexity: O(n) where n is the number of nodes in the binary tree. Space Complexity: O(n) due to the recursive stack.

Solution Code

class Solution {
    public void flatten(TreeNode root) {
        if (root == null) {
            return;
        }
        
        flatten(root.left);
        flatten(root.right);
        
        TreeNode temp = root.right;
        root.right = root.left;
        root.left = null;
        
        while (root.right != null) {
            root = root.right;
        }
        
        root.right = temp;
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 114 (Flatten Binary Tree to Linked List)?

This page provides optimized solutions for LeetCode problem 114 (Flatten Binary Tree to Linked List) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 114 (Flatten Binary Tree to Linked List)?

The time complexity for LeetCode 114 (Flatten Binary Tree to Linked List) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 114 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 114 in Java, C++, or Python.

Back to LeetCode Solutions