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
|
#include <iostream>
#include <initializer_list>
#include <utility>
class BSTree {
struct DNode {
int data;
DNode* left;
DNode* right;
DNode(int data_in, DNode* left_in=nullptr, DNode* right_in=nullptr)
: data(data_in), left(left_in), right(right_in) { }
};
DNode* root = nullptr;
static void clear(DNode*& node);
static void print(const DNode* node);
static void insert(DNode*& node, int data);
static DNode* copy(const DNode* node);
public:
BSTree() = default;
BSTree(std::initializer_list<int> il) { for (int data: il) insert(data); }
BSTree(const BSTree& tree) : root(copy(tree.root)) { }
BSTree(BSTree&& tree) : root(tree.root) { tree.root = nullptr; }
~BSTree() { clear(); }
void clear() { clear(root); }
void print() { print(root); std::cout << '\n'; }
void insert(int data) { insert(root, data); }
void insert(std::initializer_list<int> il) { for (int data: il) insert(data); }
BSTree& operator=(const BSTree& other); // copy assignment
BSTree& operator=(BSTree&& other); // move assignment
};
BSTree& BSTree::operator=(const BSTree& other) {
if (this != &other) {
clear();
root = copy(other.root);
}
return *this;
}
BSTree& BSTree::operator=(BSTree&& other) {
if (this != &other) {
clear();
root = std::exchange(other.root, nullptr);
}
return *this;
}
BSTree::DNode* BSTree::copy(const DNode* node) {
return node ? new DNode(node->data, copy(node->left), copy(node->right))
: nullptr;
}
void BSTree::insert(DNode*& node, int data) {
if (!node)
node = new DNode(data);
else if (data < node->data)
insert(node->left, data);
else
insert(node->right, data);
}
void BSTree::print(const DNode* node) {
if (!node) return;
print(node->left);
std::cout << node->data << ' ';
print(node->right);
}
void BSTree::clear(DNode*& node) {
if (!node) return;
clear(node->left);
clear(node->right);
delete node;
node = nullptr;
}
int main() {
using std::cout;
BSTree t1({5, 3, 0, 7, 4});
t1.insert({9, 1, 8, 6, 2});
cout << " t1: ";
t1.print();
cout << "Tree t2(t1)\n";
BSTree t2(t1);
cout << " t1: ";
t1.print();
cout << " t2: ";
t2.print();
cout << "Tree t3(std::move(t1))\n";
BSTree t3(std::move(t1));
cout << " t1: ";
t1.print();
cout << " t3: ";
t3.print();
cout << "t1 = t2\n";
t1 = t2;
cout << " t1: ";
t1.print();
cout << " t2: ";
t2.print();
cout << "t1 = std::move(t3)\n";
t1 = std::move(t3);
cout << " t1: ";
t1.print();
cout << " t3: ";
t3.print();
}
| |