-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryTreeToDLL.java
More file actions
80 lines (61 loc) · 1.71 KB
/
Copy pathBinaryTreeToDLL.java
File metadata and controls
80 lines (61 loc) · 1.71 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package LinkedList;
/**
* Created by rmukherj on 7/19/16.
*/
class Node {
int data;
Node left, right;
public Node(int d){
this.data = d;
left = null;
right = null;
}
}
public class BinaryTreeToDLL {
static Node root;
// head --> Pointer to head node of created doubly linked list
static Node head;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static Node prev;
private void BinaryTree2DoublyLinkedList(Node root){
if(root == null){
return;
}
BinaryTree2DoublyLinkedList(root.left);
if(prev == null){
head = root;
} else {
root.left = prev;
prev.right = root;
}
prev = root;
BinaryTree2DoublyLinkedList(root.right);
}
/* Function to print nodes in a given doubly linked list */
void printList(Node node)
{
while (node != null)
{
System.out.print(node.data + " ");
node = node.right;
}
}
// Driver program to test above functions
public static void main(String[] args)
{
// Let us create the tree as shown in above diagram
BinaryTreeToDLL tree = new BinaryTreeToDLL();
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.BinaryTree2DoublyLinkedList(root);
// Print the converted List
tree.printList(head);
}
}