include iostream include vector include string using namespace std cla

  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
121
122
123
124
125
126
127
#include <iostream>
#include <vector>
#include <string>
using namespace::std;
class Node {
private:
string data;
long index;
Node *parent;
vector<Node*> children;
void addChildren(Node *n) {
children.push_back(n);
}
public:
Node(string d, long i) {
data = d;
index = i;
parent = NULL;
}
void setParent(Node &p) {
parent = &p;
parent->children.push_back(this);
}
void setData(string d) {
data = d;
}
long getIndex(){
return index;
}
size_t GetCountOfChild() {
return children.size();
}
Node *GetParent(){
return parent;
}
string GetData() {
return data;
}
vector<Node*> GetChildren() {
return children;
}
~Node() {
}
};
class Tree {
private:
vector<Node*> nodes;
string result;
void countResult(Node *node) {
result += node->GetData();
for (size_t i = 0; i < node->GetCountOfChild(); i++) {
countResult(node->GetChildren()[i]);
}
}
public:
Tree() {}
void addNewNode(Node *p) {
nodes.push_back(p);
}
void setParentByNodeIndex(size_t child, size_t parent) {
getNodeByNodeIndex(child)->setParent(*getNodeByNodeIndex(parent));
}
void setParentByIndex(size_t child, size_t parent) {
nodes[child]->setParent(*nodes[parent]);
}
void countResult() {
for (int i = 0; i < nodes.size(); i++) {
if (nodes[i]->GetParent() == NULL) {
countResult(nodes[i]);
return;
}
}
}
Node *getNodeByNodeIndex(long index) {
for (int i = 0; i < nodes.size(); i++) {
if (nodes[i]->getIndex() == index)
return nodes[i];
}
return NULL;
}
Node *getNodeByIndex(size_t index) {
return nodes[index];
}
Node *operator[](size_t index) {
return getNodeByNodeIndex(index);
}
string Result() {
return result;
}
~Tree() {
for (int i; i < nodes.size(); i++)
delete nodes[i];
}
};
int main() {
Tree tree;
tree.addNewNode(new Node("c", 1));
tree.addNewNode(new Node("d", 2));
tree.addNewNode(new Node("*", 3));
tree.setParentByNodeIndex(1, 3);
tree.setParentByNodeIndex(2, 3);
tree.addNewNode(new Node("+", 4));
tree.addNewNode(new Node("a", 5));
tree.setParentByNodeIndex(5, 4);
tree.setParentByNodeIndex(3, 4);
tree.addNewNode(new Node("=", 6));
tree.addNewNode(new Node("b", 7));
tree.setParentByNodeIndex(7, 6);
tree.setParentByNodeIndex(4, 6);
tree.countResult();
cout << tree.Result() << endl;
return 0;
}