/
ex13.28.cpp
77 lines (74 loc) · 1.58 KB
/
ex13.28.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
class TreeNode
{
private:
std::string value;
int* count;
TreeNode *left;
TreeNode *right;
public:
TreeNode()
: value(std::string()), count(new int(1)),
left(nullptr), right(nullptr) {}
TreeNode(const TreeNode& rhs)
: value(rhs.value), count(rhs.count), left(rhs.left), right(rhs.right) {}
TreeNode& operator=(const TreeNode& rhs);
~TreeNode()
{
if (--*count == 0)
{
if (left)
{
delete left;
left = nullptr;
}
if (right)
{
delete right;
right = nullptr;
}
delete count;
count = nullptr;
}
}
};
class BinStrTree
{
private:
TreeNode *root;
public:
BinStrTree() : root(new TreeNode()) {}
BinStrTree(const BinStrTree& bst) : root(new TreeNode(*bst.root)) {}
BinStrTree& operator=(const BinStrTree& bst);
~BinStrTree() {delete root;}
};
TreeNode& TreeNode::operator=(const TreeNode& rhs)
{
++*rhs.count;
if (--*count == 0)
{
if (left)
{
delete left;
left = nullptr;
}
if (right)
{
delete right;
right = nullptr;
}
delete count;
count = nullptr;
}
value = rhs.value;
left = rhs.left;
right = rhs.right;
count = rhs.count;
return *this;
}
BinStrTree& BinStrTree::operator=(const BinStrTree& bst)
{
TreeNode* new_root = new TreeNode(*bst.root);
delete root;
root = new_root;
return *this;
}