-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinaryTreetoCList.cpp
More file actions
107 lines (77 loc) · 1.91 KB
/
binaryTreetoCList.cpp
File metadata and controls
107 lines (77 loc) · 1.91 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
#include <iostream>
#include <stdlib.h>
using namespace std;
struct node {
struct node* left;
struct node* right;
int data;
};
struct node* insert(struct node* root, int data) {
if (root == NULL) {
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return newNode;
}
if (data < root->data) {
root->left = insert(root->left,data);
} else {
root->right = insert(root->right,data);
}
return root;
}
void inOrder(struct node* root){
if (root == NULL) return;
inOrder(root->left);
cout<<root->data<<endl;
inOrder(root->right);
}
void printList(struct node* head){
cout<<"List:"<<endl;
struct node* current = head;
while (current != NULL) {
cout<<current->data<<endl;
current = current->right;
if (current == head) break;
}
}
//Join two nodes
void join(struct node* a, struct node* b){
a->right = b;
b->left = a;
}
//Join two circular Lists and return list
struct node* append(struct node* a, struct node* b){
if (a == NULL) return b;
if (b == NULL) return a;
struct node* aLast = a->left;
struct node* bLast = b->left;
join(aLast,b);
join(bLast,a);
return a;
}
struct node* treeToList(struct node* root){
if (root == NULL) return NULL;
struct node* leftList = treeToList(root->left);
struct node* rightList = treeToList(root->right);
//Leap of faith
//Make root as a single node circular list
root->right = root;
root->left = root;
//Join leftList and root
leftList = append(leftList,root);
leftList = append(leftList,rightList);
return leftList;
}
int main(){
struct node* root = NULL;
root = insert(root,4);
root = insert(root,2);
root = insert(root,3);
root = insert(root,5);
root = insert(root,1);
inOrder(root);
struct node* list = treeToList(root);
printList(list);
}