-
Notifications
You must be signed in to change notification settings - Fork 799
/
exercise13_28.h
84 lines (73 loc) · 1.31 KB
/
exercise13_28.h
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
#ifndef ex13_28_h
#define ex13_28_h
#include <string>
using std::string;
class TreeNode
{
public:
TreeNode() : value(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) { ++*count; }
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;
}
}
private:
std::string value;
int *count;
TreeNode *left;
TreeNode *right;
};
TreeNode& TreeNode::operator=(const TreeNode &rhs)
{
++*rhs.count;
if (--*count == 0)
{
if (left)
{
delete left;
}
if (right)
{
delete right;
}
delete count;
}
value = rhs.value;
left = rhs.left;
right = rhs.right;
count = rhs.count;
return *this;
}
class BinStrTree
{
public:
BinStrTree() : root(new TreeNode()) {}
BinStrTree(const BinStrTree &bst) : root(new TreeNode(*bst.root)) {}
BinStrTree& operator=(const BinStrTree &bst);
~BinStrTree() { delete root; }
private:
TreeNode *root;
};
BinStrTree& BinStrTree::operator=(const BinStrTree &bst)
{
TreeNode *new_root = new TreeNode(*bst.root);
delete root;
root = new_root;
return *this;
}
#endif