...

/

Flatten Binary Tree to Linked List

Flatten Binary Tree to Linked List

Try to solve the Flatten Binary Tree to Linked List problem.

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.js in the following coding playground.

JavaScript
usercode > main.js
import {TreeNode} from './ds_v1/BinaryTree.js';
// Definition of a binary tree node
// class TreeNode {
// constructor(data) {
// this.data = data;
// this.left = null;
// this.right = null;
// }
// }
export function flattenTree(root) {
// Replace this placeholder return statement with your code
return root;
}
Flatten Binary Tree to Linked List

Access this course and 1200+ top-rated courses and projects.