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.
We'll cover the following...
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.java in the following coding playground.
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 codereturn root;}}