This repository has been archived by the owner on Oct 23, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
Copy paththreaded binary tree.cpp
138 lines (110 loc) · 2.47 KB
/
threaded binary tree.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include<bits/stdc++.h>
using namespace std;
struct Node
{
struct Node *left, *right;
int info;
bool lthread;
bool rthread;
};
struct Node *insert(struct Node *root, int ikey)
{
Node *ptr = root;
Node *par = NULL;
while (ptr != NULL)
{
if (ikey == (ptr->info))
{
printf("Duplicate Key !\n");
return root;
}
par = ptr;
if (ikey < ptr->info)
{
if (ptr -> lthread == false)
ptr = ptr -> left;
else
break;
}
else
{
if (ptr->rthread == false)
ptr = ptr -> right;
else
break;
}
}
Node *tmp = new Node;
tmp -> info = ikey;
tmp -> lthread = true;
tmp -> rthread = true;
if (par == NULL)
{
root = tmp;
tmp -> left = NULL;
tmp -> right = NULL;
}
else if (ikey < (par -> info))
{
tmp -> left = par -> left;
tmp -> right = par;
par -> lthread = false;
par -> left = tmp;
}
else
{
tmp -> left = par;
tmp -> right = par -> right;
par -> rthread = false;
par -> right = tmp;
}
return root;
}
struct Node *inorderSuccessor(struct Node *ptr)
{
if (ptr -> rthread == true)
return ptr->right;
ptr = ptr -> right;
while (ptr -> lthread == false)
ptr = ptr -> left;
return ptr;
}
void inorder(struct Node *root)
{
if (root == NULL)
printf("Tree is empty");
struct Node *ptr = root;
while (ptr -> lthread == false)
ptr = ptr -> left;
while (ptr != NULL)
{
printf("%d ",ptr -> info);
ptr = inorderSuccessor(ptr);
}
}
void preorder(struct Node *root){
if (root == NULL)
printf("Tree is empty");
struct Node *ptr = root;
printf("%d ",ptr -> info);
if(ptr->lthread==false)
preorder(ptr->left);
if(ptr->rthread==false)
preorder(ptr->right);
}
int main()
{
int n, arr[100];
struct Node *root = NULL;
cout<<"Enter no of nodes of tree.\n";
cin>>n;
cout<<"Enter "<<n<<" numbers.\n";
for(int i=0;i<n;i++){
cin>>arr[i];
root = insert(root, arr[i]);
}
inorder(root);
cout<<endl;
preorder(root);
return 0;
}