-
Notifications
You must be signed in to change notification settings - Fork 0
/
BST.cpp
116 lines (103 loc) · 2.48 KB
/
BST.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
/*
Author: Gwyn Gras-Usry
Date: 3/19/22
Description: BST functions
*/
#include "BST.hpp"
BST::BST() {
mpRoot = nullptr;
fstream fileStream("MorseTable.txt");
char line[100];
Data newData;
while (!fileStream.eof()) {
fileStream.getline(line, 100, ' ');
newData.setCharacter(line[0]);
fileStream.getline(line, 100, '\n');
newData.setMorseCode(line);
insert(newData);
}
fileStream.close();
}
BST::~BST() {
this->destroyTree(this->mpRoot);
}
void BST::destroyTree(BSTNode* pTree) {
if (pTree != nullptr){
destroyTree(pTree->getLeftNode());
destroyTree(pTree->getRightNode());
delete pTree;
}
}
void BST::insert(Data &newData) {
insert(this->mpRoot, newData);
}
void BST::insert(BSTNode* pTree, Data& newData) {
if (pTree == nullptr) { // empty tree
this->mpRoot = new BSTNode(newData.getCharacter(), newData.getMorseCode());
}
else {
if ((*pTree).getCharacter() < newData.getCharacter()) {
if (pTree->getRightNode() == nullptr) {
pTree->setRightNode(new BSTNode(newData.getCharacter(), newData.getMorseCode()));
}
else {
insert(pTree->getRightNode(), newData);
}
}
else if ((*pTree).getCharacter() > newData.getCharacter()) {
if (pTree->getLeftNode() == nullptr) {
pTree->setLeftNode(new BSTNode(newData.getCharacter(), newData.getMorseCode()));
}
else {
insert(pTree->getLeftNode(), newData);
}
}
}
}
void BST::print(void) {
print(this->mpRoot);
cout << endl;
}
void BST::print(BSTNode* pTree) {
if (pTree != nullptr) {
print(pTree->getLeftNode());
cout << pTree->getCharacter() << ", ";
print(pTree->getRightNode());
}
}
string BST::search(char c) {
string s = search(this->mpRoot, c);
return s;
}
string BST::search(BSTNode* pTree, char c) {
string result = " ";
if (pTree == nullptr) { // empty tree
return " ";
}
else {
if ((*pTree).getCharacter() == c) {
return (*pTree).getMorseCode();
}
else if (c > (*pTree).getCharacter()) { // go right
return search(pTree->getRightNode(), c);
}
else if (c < (*pTree).getCharacter()) { // go left
return search(pTree->getLeftNode(), c);
}
}
}
void convertToMorse(fstream& filestream) {
char line[100];
int i = 0;
BST bst;
filestream.getline(line, 100, '\n');
while (!filestream.eof()) {
while (line[i] != '\n') {
cout << bst.search(toupper(line[i])) << " ";
i++;
}
i = 0;
filestream.getline(line, 100, '\n');
cout << endl;
}
}