700615. Leaves to DLL
Here is a detailed Markdown blog post for the "Leaves to DLL" problem:
Leaves to DLL
Slug: leaves-to-dll
Difficulty: Medium
Id: 700615
Topic Tags: Linked List, Tree, Data Structures
Company Tags: Amazon, Linkedin
Summary
The Leaves to DLL problem involves transforming a given binary tree into a doubly linked list (DLL) where the nodes are connected in such a way that each node points to its left child and right sibling. The task is to traverse the original tree from top to bottom, converting leaves (nodes with no children) into DLL nodes while maintaining their relative order.
Detailed Explanation
To solve this problem, we'll first need to design an algorithm to convert the binary tree into a DLL. We can achieve this by performing a depth-first traversal of the tree and constructing the DLL as we go.
Here's a step-by-step breakdown of the solution:
- Initialize an empty DLL head node.
- Perform a pre-order DFS traversal of the original binary tree, starting from the root node.
- For each visited node:
- If the node is a leaf (i.e., it has no children), create a new DLL node and add it to the end of the DLL.
- If the node has children, recursively traverse its left child and then its right child.
- Return the head of the constructed DLL.
Time complexity: O(n), where n is the number of nodes in the binary tree, since we visit each node once. Space complexity: O(h), where h is the height of the binary tree, due to the recursive function calls.
Optimized Solutions
Java
class Node {
int value;
Node left, right;
public Node(int val) {
value = val;
left = right = null;
}
}
public class BinaryTreeToDLL {
public static Node treeToDLL(Node root) {
if (root == null) return null;
Node current = root;
while (current != null && current.left != null) {
current = current.left;
}
// Construct the DLL
Node dllHead = null;
Node prev = null;
while (current != null) {
Node next = current.right;
if (dllHead == null) {
dllHead = current;
prev = dllHead;
} else {
prev.right = current;
prev = current;
}
current = next;
}
return dllHead;
}
}