-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathBT_Problem_18.java
More file actions
62 lines (52 loc) · 1.13 KB
/
Copy pathBT_Problem_18.java
File metadata and controls
62 lines (52 loc) · 1.13 KB
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package trees.binaryTree;
/*
* Problem Title :- Convert Binary tree into Doubly Linked List
*/
public class BT_Problem_18 {
static class Node{
int data;
Node left, right;
Node(int data){
this.data = data;
left = right = null;
}
}
Node root, head;
static Node prev = null;
void BinaryTree2DLL(Node root){
// Base case
if (root == null)
return;
// Recursively convert left subtree
BinaryTree2DLL(root.left);
// Now convert this node
if (prev == null)
head = root;
else {
root.left = prev;
prev.right = root;
}
prev = root;
BinaryTree2DLL(root.left);
}
void printList(Node node) {
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
public static void main(String[] args) {
BT_Problem_18 tree = new BT_Problem_18();
tree.root = new Node(10);
tree.root.left = new Node(12);
tree.root.right = new Node(15);
tree.root.left.left = new Node(25);
tree.root.left.right = new Node(30);
tree.root.right.left = new Node(36);
// convert to DLL
tree.BinaryTree2DLL(tree.root);
// Print the converted List
tree.printList(tree.head);
}
}