Website Summary Files Commits Branches @commit @diff @stats
path: root / Seminar08 / tree-utils.h
blob: ad3be90c2d27926f029f80bca2cce67c5225c443 (plain) (blame)
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
#ifndef TREE_UTIL_IMPL
#define TREE_UTIL_IMPL

#include<iostream>
#include<string>
#include<fstream>

// Важни неща:
template<class T>
struct Tree {
    T data;
    Tree* left;
    Tree* right;

    Tree(T data, Tree<T>* l = nullptr, Tree<T>* r = nullptr) : data {data}, left {l}, right {r} {}
};

template<class T>
void freeTree(Tree<T>* t) {
    if(t == nullptr)
        return;
    freeTree(t->left);
    freeTree(t->right);
    delete t;
}

template<class T>
void insertInBST(Tree<T>*& t, const T& elem) {
    if (t == nullptr) {
        t = new Tree<T>(elem);
        return;
    }
    else if (t->data < elem) {
        insertInBST(t->right, elem);
    }
    else {
        insertInBST(t->left, elem);
    }
}

template<class T>
Tree<T>* getMinRightNode(const Tree<T>* t) {
	assert(t != nullptr);

	Tree<T>* iter = t;

	while (iter->left) {
		iter = iter->left;
	}
	return iter;
}

template<class T>
bool removeElement(Tree<T>*& t, const T& elem) {
	if (t == nullptr)
		return false;

	if (t->data > elem) {
		return removeElement(t->left, elem);
	}
	else if (t->data < elem) {
		return removeElement(t->right, elem);
	}
	else {																// Намерили сме елемента
		if (!t->left && !t->right) {									// Листо
			delete t;
			t = nullptr; //!!
		}
		else if (!t->left && t->right) {								// Има само дясно поддърво
			Tree<T>* toDelete = t;
			t = t->right;
			delete toDelete;
		}
		else if (t->left && !t->right) {								// Има само ляво поддърво
			Tree<T>* toDelete = t;
			t = t->left;
			delete toDelete;
		}
		else {															// Вътрешен връх. 
			T newData = getMinRightNode(t->right)->data;
			t->data = newData;
			removeElement(t->right, newData);
		}
		return true;
	}
}

template<class T>
bool containsBST(const Tree<T>* t, const T& elem) {
	if (t == nullptr)
		return false;

	if (t->data == elem)
		return true;

	if (t->data < elem)
		return containsBST(t->right, elem);

	return containsBST(t->left, elem);
}

// Неща за мое удобство, не е нужно да ги четете:

// Взето от:
// https://stackoverflow.com/questions/36802354/print-binary-tree-in-a-pretty-way-using-c
template<class T>
void printBT(const std::string& prefix, const Tree<T>* node, bool isLeft) {
    if(node != nullptr) {
        std::cout << prefix;

        std::cout << (isLeft ? "|--" : "`--" );

        std::cout << node->data << std::endl;

        printBT( prefix + (isLeft ? "|   " : "    "), node->left, true);
        printBT( prefix + (isLeft ? "|   " : "    "), node->right, false);
    }
}

template<class T>
void printTree(const Tree<T>* node) {
    printBT("", node, false);    
}

// Следващите две функции са малко по - красив начин да изпринтим дърво, но го конвертира къмм LaTeX документ
// Когато извикате exportToTex("file.txt") ще ви създаде фейл с код. 
// Пейстнете кода в overleaf.com и ще ви излезе дървото.

// Не е перфектно но пък е по - удобно от конзолата. Това е за демонстрации, не е нужно да го учите или разбирате.
template<class T>
void recFillFileStream(std::ofstream& outFile, const Tree<T>* r) {
	if(r == nullptr)
		return;

	outFile << "[" << r->data << " ";
	recFillFileStream(outFile, r->left);
	recFillFileStream(outFile, r->right);

	outFile << "]";
}

template<class T>
void exportToTex(const Tree<T>* root, const char* filePath) {
	std::ofstream outFile(filePath, std::ios::trunc);

	outFile << "\\documentclass[tikz,border=10pt]{standalone}" << std::endl;
	outFile << "\\usepackage[linguistics]{forest}" << std::endl;
	outFile << "\\begin{document}" << std::endl;
	outFile << "\\begin{forest}" << std::endl;

	recFillFileStream(outFile, root);

	outFile << "\\end{forest}";
	outFile << "\\end{document}";

    outFile.close();
}

#endif