Search⌘ K
AI Features

Flatten Binary Tree to Linked List

Explore how to transform a binary tree into a flattened linked list where each left child pointer is null and the right points to the next node in preorder sequence. Understand the problem constraints and practice implementing the solution using depth-first search. This lesson helps you develop skills for manipulating tree structures and applying traversal patterns effectively.

Statement

Given the root of a binary tree, the task is to flatten the tree into a linked list using the same TreeNode class. The left child pointer of each node in the linked list should always be NULL, and the right child pointer should point to the next node in the linked list. The nodes in the linked list should be in the same order as that of the preorder traversal of the given binary tree.

Constraints:

  • 100-100 \leq Node.data 100\leq 100.
  • The tree contains nodes in the range [1,500][1, 500].

Examples

Understand the problem

Let’s take a moment to make sure you’ve correctly understood the problem. The quiz below helps you check if you’re solving the correct problem:

Flatten Binary Tree to Linked List

1.

Choose the correct flattened linked list for the given binary tree:

    3
   / \
  2   17
 / \  / \
1  4 19  5
A.

3 → 2 → 17 → 1 → 4 → 19 → 5

B.

3 → 2 → 1 → 4 → 17 → 19 → 5

C.

3 → 2 → 1 → 4 → 19 → 17 → 5

D.

17 → 19 → 5 → 3 → 2 → 1 → 4


1 / 2

Figure it out!

We have a game for you to play. Rearrange the logical building blocks to develop a clearer understanding of how to solve this problem.

Sequence - Vertical
Drag and drop the cards to rearrange them in the correct sequence.

1
2
3
4
5
6

Try it yourself

Implement your solution in main.java in the following coding playground.

Java
usercode > Solution.java
import java.util.*;
import ds_v1.BinaryTree.TreeNode;
// Definiton of a binary tree node class
// class TreeNode<T> {
// T data;
// TreeNode<T> left;
// TreeNode<T> right;
// TreeNode(T data) {
// this.data = data;
// this.left = null;
// this.right = null;
// }
// }
public class Solution {
public static TreeNode<Integer> flattenTree(TreeNode<Integer> root) {
// Replace this placeholder return statement with your code
return root;
}
}
Flatten Binary Tree to Linked List