-
Notifications
You must be signed in to change notification settings - Fork 0
/
Tree.h
120 lines (101 loc) · 1.84 KB
/
Tree.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
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
#ifndef ___TREE_H___
#define ___TREE_H___
#include <vector>
template<typename Element>
class TreeNode
{
private:
public:
int layer; //root is the highest layer
Element e;
TreeNode* parent;
std::vector<TreeNode< Element >*> children;
TreeNode(Element _e);
virtual ~TreeNode();
};
template<typename Element>
TreeNode< Element >::TreeNode(Element _e)
{
e = _e;
parent = NULL;
}
template<typename Element>
TreeNode< Element >::~TreeNode()
{
}
template<typename Element>
class Tree
{
private:
TreeNode< Element >* root;
int currentLayer;
std::vector<TreeNode< Element >*> index;
public:
int PushAsParent(Element _e);
int PushAsChild(Element _e);
Element operator[](int _id)
{
return index[_id]->e;
}
int GetLayer(int _id)
{
return index[_id]->layer;
}
int size()
{
return index.size();
}
Tree();
virtual ~Tree();
};
template<typename Element>
int Tree< Element >::PushAsParent(Element _e)
{
TreeNode< Element >* tmpTreeNode = new TreeNode< Element >(_e);
tmpTreeNode->layer = currentLayer;
index.push_back(tmpTreeNode);
if(root == NULL)
{
root = tmpTreeNode;
}
else
{
TreeNode< Element >* tmpRoot;
tmpRoot = root;
root->parent = tmpTreeNode;
root = tmpTreeNode;
root->children.push_back(tmpRoot);
}
currentLayer++;
}
template<typename Element>
int Tree< Element >::PushAsChild(Element _e)
{
TreeNode< Element >* tmpTreeNode = new TreeNode< Element >(_e);
tmpTreeNode->layer = currentLayer - 2;
index.push_back(tmpTreeNode);
if(root == NULL)
{
return -1;
}
else
{
tmpTreeNode->parent = root;
root->children.push_back(tmpTreeNode);
}
}
template<typename Element>
Tree< Element >::Tree()
{
currentLayer = 1;
root = NULL;
}
template<typename Element>
Tree< Element >::~Tree()
{
for(int i = 0; i < index.size(); i++)
{
delete index[i];
}
}
#endif //___TREE_H___