Leetcode 114: Flatten Binary Tree to Linked List

grid47
grid47
Exploring patterns and algorithms
Oct 26, 2024 5 min read

A soft tree smoothly transforming into a linear, glowing list of nodes, symbolizing a flattened structure.
Solution to LeetCode 114: Flatten Binary Tree to Linked List Problem

Given the root of a binary tree, flatten the tree into a ’linked list’ where each node’s right pointer points to the next node in pre-order traversal, and the left pointer of all nodes is null. The ’linked list’ should maintain the same order as a pre-order traversal of the binary tree.
Problem
Approach
Steps
Complexity
Input: The input consists of the root of a binary tree. The tree is represented as an array of node values, with null indicating missing nodes.
Example: Input: root = [3, 2, 5, 1, null, null, 6]
Constraints:
• The number of nodes in the tree is between 0 and 2000.
• Node values are between -100 and 100.
Output: The output should be the flattened tree represented as a linked list, where each node points to the next node in pre-order traversal, and the left pointer of each node is null.
Example: Output: [3,null,2,null,1,null,5,null,6]
Constraints:
• The right child pointer of each node should point to the next node in pre-order traversal.
• The left child pointer of each node should be null.
Goal: The goal is to flatten the binary tree such that it behaves like a linked list, while maintaining the pre-order traversal order.
Steps:
• Start from the root node and recursively flatten the left subtree.
• Rearrange the tree so that the right child points to the flattened left subtree.
• Set the left child of all nodes to null.
• Repeat the process for the right subtree.
Goal: The tree will have between 0 and 2000 nodes. The node values will range from -100 to 100.
Steps:
• The number of nodes is between 0 and 2000.
• Node values are in the range [-100, 100].
Assumptions:
• The tree is a valid binary tree.
Input: Input: root = [3,2,5,1,null,null,6]
Explanation: In pre-order traversal, the tree will be visited in this order: 3, 2, 1, 5, 6. The flattened tree should thus look like [3,null,2,null,1,null,5,null,6].

Input: Input: root = []
Explanation: If the input is an empty tree (root is null), the output should also be an empty list.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus