Flatten Binary Tree to Linked List
Explore how to flatten a binary tree into a linked list where each left child is null and right child points to the next node following pre-order traversal. Understand the step-by-step algorithm and analyze both time and space complexity to apply this technique efficiently in coding interviews.
We'll cover the following...
Description
We are given the root of a binary tree. We have to flatten the tree into a linked list. The left child of the linked list is always null, and the right child points to the next node in the list. The nodes in the linked list should be in the same order as the pre-order traversal of the given binary tree.
Constraints
- -100 <= ‘Node.val’ <= 100
- The tree contains nodes in the range [0, 2000].
Let’s see how a flattened tree looks like in the illustration below:
Coding exercise
Solution
We will flatten the given binary tree into the linked list. We will keep the linked list in the pre-order traversal of the binary tree. We will be traversing the tree starting from the root.
Let’s see the following algorithm to implement the described problem.
-
First, we will implement the loop that keeps ...