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:
-
Node.data
. - The tree contains nodes in the range .
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
Choose the correct flattened linked list for the given binary tree:
3
/ \
2 17
/ \ / \
1 4 19 5
3 → 2 → 17 → 1 → 4 → 19 → 5
3 → 2 → 1 → 4 → 17 → 19 → 5
3 → 2 → 1 → 4 → 19 → 17 → 5
17 → 19 → 5 → 3 → 2 → 1 → 4
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.
Try it yourself
Implement your solution in main.js
in the following coding playground.
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 codereturn root;}