Flattening a binary tree to a linked list is a common problem in data structures and algorithms. It involves transforming a binary tree into a structure that resembles a linked list, where each node has no left child and the right child points to the next node in the pre-order traversal.
Let's dive into this problem and explore an efficient solution using Java.
Given a binary tree, flatten it into a linked list in-place. The "flattened" tree should use the right child pointers to link the nodes, and all left child pointers should be set to null.
For example, given the following binary tree:
1
/ \
2 5
/ \ \
3 4 6
The flattened tree should look like:
1
\
2
\
3
\
4
\
5
\
6
We'll use a pre-order traversal approach to flatten the tree. The key steps are:
Let's implement this solution in Java:
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int val) { this.val = val; } } class Solution { public void flatten(TreeNode root) { if (root == null) { return; } // Recursively flatten left and right subtrees flatten(root.left); flatten(root.right); // Store the right subtree TreeNode rightSubtree = root.right; // Make the flattened left subtree the right child root.right = root.left; root.left = null; // Find the end of the new right subtree TreeNode current = root; while (current.right != null) { current = current.right; } // Attach the original right subtree current.right = rightSubtree; } }
Let's break down the flatten
method:
We first check if the root is null. If so, we return as there's nothing to flatten.
We recursively flatten the left and right subtrees. This ensures that all subtrees are flattened before we process the current node.
We store the right subtree in a variable rightSubtree
. We'll need this later.
We make the flattened left subtree the new right child of the current node. This is a key step in the flattening process.
We set the left child to null, as per the problem requirements.
We then traverse to the end of this newly formed right subtree (which was originally the left subtree).
Finally, we attach the original right subtree (stored in rightSubtree
) to the end of the current right subtree.
Flattening a binary tree to a linked list is an interesting problem that combines tree traversal with in-place manipulation of the tree structure. By using a pre-order traversal approach, we can efficiently transform the tree while maintaining its original order.
This problem is a great example of how understanding tree structures and traversal techniques can be applied to solve complex transformation tasks. Practice implementing this solution to sharpen your skills with binary trees and recursive algorithms.
06/12/2024 | DSA
23/09/2024 | DSA
15/11/2024 | DSA
08/12/2024 | DSA
13/10/2024 | DSA
15/11/2024 | DSA
23/09/2024 | DSA
15/11/2024 | DSA
15/11/2024 | DSA
08/12/2024 | DSA
13/10/2024 | DSA
16/11/2024 | DSA