-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBinary2DoublyLinkedList.cpp
103 lines (86 loc) · 2.46 KB
/
Binary2DoublyLinkedList.cpp
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
// A C++ program for in-place conversion of Binary Tree to DLL
#include <iostream>
using namespace std;
/* A binary tree node has data, and left and right pointers */
struct node
{
int data;
node* left;
node* right;
};
node* BinaryTree2DLL(node* root) {
if (root->left == NULL && root->right==NULL){
return root;
}
node* a = BinaryTree2DLL(root->left);
root->left = a;
if (a) a->right = root;
node* b = BinaryTree2DLL(root->right);
root->right = b;
if (b) b->left = root;
return a;
}
// A simple recursive function to convert a given Binary tree to Doubly
// Linked List
// root --> Root of Binary Tree
// head --> Pointer to head node of created doubly linked list
void BinaryTree2DoubleLinkedList(node *root, node **head)
{
// Base case
if (root == NULL) return;
// Initialize previously visited node as NULL. This is
// static so that the same value is accessible in all recursive
// calls
static node* prev = NULL;
// Recursively convert left subtree
BinaryTree2DoubleLinkedList(root->left, head);
// Now convert this node
if (prev == NULL)
*head = root;
else
{
root->left = prev;
prev->right = root;
}
prev = root;
// Finally convert right subtree
BinaryTree2DoubleLinkedList(root->right, head);
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
node* newNode(int data)
{
node* new_node = new node;
new_node->data = data;
new_node->left = new_node->right = NULL;
return (new_node);
}
/* Function to print nodes in a given doubly linked list */
void printList(node *node)
{
cout<<"Sorted List "<<endl;
while (node!=NULL)
{
cout << node->data << " ";
node = node->right;
}
}
/* Driver program to test above functions*/
int main()
{
// Let us create the tree shown in above diagram
node *root = newNode(10);
root->left = newNode(12);
root->right = newNode(15);
root->left->left = newNode(25);
root->left->right = newNode(30);
root->right->left = newNode(36);
// Convert to DLL
//node *head = NULL;
//BinaryTree2DoubleLinkedList(root, &head);
// Print the converted list
//printList(head);
node* head1 = BinaryTree2DLL(root);
printList(head1);
return 0;
}