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
|
#include <iostream>
#include <fstream>
#include <vector>
struct Node {
int data;
int left, right;
Node(int d, int l=-1, int r=-1) : data{d}, left{l}, right{r} {}
};
int insert(int node, std::vector<Node*>& v, int data) {
if (node == -1) {
v.push_back(new Node(data));
return v.size() - 1;
}
if (data < v[node]->data)
v[node]->left = insert(v[node]->left, v, data);
else
v[node]->right = insert(v[node]->right, v, data);
return node;
}
void print(int node, const std::vector<Node*>& v) {
if (node == -1) return;
print(v[node]->left, v);
std::cout << v[node]->data << ' ';
print(v[node]->right, v);
}
void save(const std::string& filename, int root, const std::vector<Node*>& v) {
std::ofstream fout(filename);
fout << root << '\n';
for (int i = 0; i < int(v.size()); ++i)
fout << v[i]->data << ' ' << v[i]->left << ' ' << v[i]->right << '\n';
}
int restore(const std::string& filename, std::vector<Node*>& v) {
std::ifstream fin(filename);
int root, node, left, right;
fin >> root;
for (int i = 0; fin >> node >> left >> right; ++i)
v.push_back(new Node(node, left, right));
return root;
}
void clear(int& root, std::vector<Node*>& v) {
root = -1;
for (int i = 0; i < int(v.size()); ++i)
delete v[i];
v.clear();
}
int main() {
std::vector<Node*> v;
int root = -1;
for (int n: {6, 3, 4, 9, 0, 2, 8, 5, 1, 7})
root = insert(root, v, n);
print(root, v);
std::cout << '\n';
// requires file system access
/*
save("save.txt", root, v);
clear(root, v);
root = restore("save.txt", v);
print(root, v);
std::cout << '\n';
*/
clear(root, v);
}
|