-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathThreaded_Binary_Tree.cpp
More file actions
142 lines (120 loc) · 2.58 KB
/
Copy pathThreaded_Binary_Tree.cpp
File metadata and controls
142 lines (120 loc) · 2.58 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
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
139
140
141
#include <bits/stdc++.h>
using namespace std;
struct treenode
{
int info;
int ltag;
int rtag;
struct treenode *left;
struct treenode *right;
};
struct treenode* insertion(struct treenode *root, int data)
{
treenode *ptr = root;
treenode *par = NULL;
while (ptr != NULL)
{
par = ptr;
if (data < ptr->info)
{
if (ptr -> ltag == 0)
ptr = ptr -> left;
else
break;
}
else
{
if (ptr->rtag == 0)
ptr = ptr -> right;
else
break;
}
}
//creating a new node
struct treenode *newnode = new treenode;
newnode->info = data;
newnode->ltag = 1;
newnode->rtag = 1;
if(par == NULL)
{
root = newnode;
newnode->left = NULL;
newnode->right = NULL;
}
else if(data < par->info)
{
newnode->left = par->left;
newnode->right = par;
par->ltag = 0;
par->left = newnode;
}
else
{
newnode->left = par;
newnode->right = par->right;
par->rtag = 0;
par->right = newnode;
}
return root;
}
struct treenode *inorderSuccessor(struct treenode *root)
{
if(root->rtag == 1)
return root->right;
root = root->right;
while(root->ltag == 0)
root = root->left;
return root;
}
void inorder(struct treenode *root)
{
struct treenode *temp = root;
if (root == NULL)
cout<<"Tree is empty";
while(temp->ltag == 0)
temp = temp->left;
while(temp != NULL)
{
cout<<temp->info<<" ";
temp = inorderSuccessor(temp);
}
}
int main()
{
int data,choice;
struct treenode *root = NULL;
while(1)
{
cout<<"\n1. Create tree"<<endl;
cout<<"2. In-order traversal"<<endl;
cout<<"3. EXIT"<<endl;
cout<<"Enter your choice : ";
cin>>choice;
switch(choice)
{
case 1:
{
while(1)
{
cout<<"Enter element or press -1 : ";
cin>>data;
if(data == -1)
break;
else
root = insertion(root , data);
}
break;
}
case 2:
cout<<"\nIn-order traversal is : ";
inorder(root);
break;
case 3:
exit(0);
break;
default :
cout<<"\nINVALID CHOICE"<<endl;
}
}
return 0;
}