-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathbinary-tree-to-dll.java
More file actions
33 lines (27 loc) · 929 Bytes
/
binary-tree-to-dll.java
File metadata and controls
33 lines (27 loc) · 929 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution
{
Node prev = null; // To store the previously visited node
Node head = null; // To store the head of the DLL
// Function to convert binary tree to doubly linked list and return it.
Node bToDLL(Node root)
{
// Base case
if (root == null) return null;
// Recursively convert the left subtree
bToDLL(root.left);
// Now, process the current node
if (prev == null) {
// This is the leftmost node, which will be the head of the DLL
head = root;
} else {
// Link the previous node with the current node
root.left = prev;
prev.right = root;
}
// Move the prev pointer to the current node
prev = root;
// Recursively convert the right subtree
bToDLL(root.right);
return head; // Return the head of the doubly linked list
}
}