Repository navigation
Expand file tree
/
Copy pathTree.cpp
More file actions
138 lines (124 loc) · 1.85 KB
/
Copy pathTree.cpp
File metadata and controls
138 lines (124 loc) · 1.85 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
#include <iostream>
using namespace std;
#include <queue>
class Node
{public:
int data;
Node* left;
Node* right;
Node(int a)
{
data = a;
left = NULL;
right = NULL;
}
};
bool sNT(int a)
{
if(a<=1) return false;
for(unsigned int i =2; i<a; i++)
{
if(a%i==0)
return false;
}
return true;
}
class Tree
{
private:
Node* root;
void _preOrder(Node* temp)
{
if(temp==NULL)
return;
else
{
cout<<temp->data<<" ";
_preOrder(temp->left);
_preOrder(temp->right);
}
}
void _inOrder(Node* temp)
{
if(temp==NULL)
return;
else
{
_preOrder(temp->left);
cout<<temp->data<<" ";
_preOrder(temp->right);
}
}
public:
Tree()
{
root = NULL;
}
void Insert(int a)
{
if(root== NULL)
root = new Node(a);
else
{
queue<Node*> q;
q.push(root);
while(!q.empty())
{
Node* temp = q.front();
//cout<<temp->data<<" ";
if((!sNT(a)) && temp->left == NULL )
{
temp->left = new Node(a);
//cout<<temp->left->data<<" ";
return;
}
//else q.push(root->left);
if((sNT(a)) && temp->right == NULL )
{
temp->right = new Node(a);
//cout<<temp->right->data<<" ";
return;
}
//else q.push(root->right);
if(sNT(a))
{
if(temp -> right != NULL)
q.push(temp->right);
if(temp -> left != NULL)
q.push(temp->left);
}
else
{
if(temp -> left != NULL)
q.push(temp->left);
if(temp -> right != NULL)
q.push(temp->right);
}
q.pop();
}
}
}
void preOrder()
{
_preOrder(root);
}
void inOrder()
{
_inOrder(root);
}
};
int main()
{
int n;
cin>>n;
Tree myTree;
for(unsigned int i =0; i<n;i++)
{
int temp;
cin>>temp;
myTree.Insert(temp);
}
myTree.preOrder();cout<<endl;
myTree.inOrder();cout<<endl;
return 0;
}