-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreebackend.cpp
More file actions
312 lines (278 loc) · 8.52 KB
/
Copy pathTreebackend.cpp
File metadata and controls
312 lines (278 loc) · 8.52 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#include "TreeBackend.hpp"
#include <algorithm>
#include <QDebug>
void TreeBackend::createTree(const QString &exp)
{
nodes.clear();
lines.clear();
idCounter = 0;
nodeStack.clear();
opStack.clear();
root = nullptr;
parseExpression(exp);
putDepth(root, 0);
putId(root);
res = evaluate(root);
}
QVariantList TreeBackend::denseNode(int width, int height)
{ // 给出node列表
// id, x, y, label
int maxDepth = getMaxDepth(root);
int singleWidth = width / (idCounter + 1);
int singleHeight = height / (maxDepth + 1);
setLocation(root, singleWidth, singleHeight);
return nodes;
}
QVariantList TreeBackend::denseLine()
{ // 给出line列表
// from, to
setFromTo(root);
return lines;
}
QString TreeBackend::sum()
{
return QString::number(res);
}
void TreeBackend::parseExpression(const QString &exp)
{ // 解析数据并塞入两个栈(支持一元 +/-,如 -3、2*-3、-(1+2))
double temp = 0.0;
bool expectOperand = true; // 当前是否期望读取“操作数”(数字/左括号/一元符号)
int sign = +1; // 收集一元 +/-,允许连续:--3、+-+3
for (int i = 0; i < exp.length(); i++) //做大循环,对数字,括号,运算符分别处理
{
QChar ch = exp[i];
if (ch.isSpace())
continue;
// 1) 一元 +/-(仅在期望操作数时生效)
if (expectOperand && (ch == '+' || ch == '-')) //在一开始就判断期待数
{
if (ch == '-')
sign = -sign;
continue;
}
// 2) 数字(含小数)
if (ch.isDigit() || ch == '.')
{
bool dotSeen = false;
double factor = 0.1;
temp = 0.0;
while (i < exp.length() && (exp[i].isDigit() || exp[i] == '.'))
{
if (exp[i].isDigit() && !dotSeen)
{
temp = temp * 10 + exp[i].digitValue();
}
else if (exp[i].isDigit() && dotSeen)
{
temp = temp + exp[i].digitValue() * factor;
factor *= 0.1;
}
else if (exp[i] == '.')
{
if (dotSeen) //如果已经见过小数点
{
emit errorOccurred(QString("一个数中不能有多个小数点"));
root = nullptr;
return;
break;
}
dotSeen = true;
}
i++;
}
i--; // while 多走了一格,回退
temp *= sign;
sign = +1;
treeNode *node = new treeNode();
node->type = NUM;
node->v.num = temp;
nodeStack.push_back(node);
expectOperand = false; //数字后面没有期待数
continue;
}
// 3) 左括号
if (ch == '(')
{
if (sign == -1) //!!!!!!,如果-是在()前面出现的,就自己加一个0节点,形成0-()的形式,ai666啊
{
treeNode *zero = new treeNode();
zero->type = NUM;
zero->v.num = 0.0;
nodeStack.push_back(zero);
// 压入一个二元减号,遵循优先级/左结合
while (!opStack.isEmpty() && opStack.back() != '(' &&
precedence(opStack.back()) >= precedence('-'))
{
reduceOnce();
}
opStack.push_back('-');
sign = +1;
}
opStack.push_back('(');
expectOperand = true; //左括号后面有期待数
continue;
}
// 4) 右括号
if (ch == ')')
{
while (!opStack.isEmpty() && opStack.back() != '(')
reduceOnce();
if (!opStack.isEmpty() && opStack.back() == '(')
opStack.pop_back();
else
{
emit errorOccurred(QString("多余右括号")); //发现多余右括号
}
expectOperand = false; //右括号后面没有
continue;
}
// 5) 二元运算符
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
if (expectOperand) //实际上这里不会出现+和-的情况,因为在一开始就判断过,这里只有*/遇见期待数的情况
{
emit errorOccurred(QString("遇到意外的运算符 '%1'").arg(ch)); //占位符写法
}
while (!opStack.isEmpty() && opStack.back() != '(' && //如果碰到左括号就停
precedence(opStack.back()) >= precedence(ch))
{
reduceOnce();
}
opStack.push_back(ch);
expectOperand = true; //符号后面有期待数
continue;
}
emit errorOccurred(QString("遇到意外的字符 '%1'").arg(ch));
}
// 扫尾归约
while (!opStack.isEmpty())
{
if (opStack.back() == '(')
{
emit errorOccurred(QString("多余左括号")); //发现多余左括号
opStack.pop_back();
continue;
}
reduceOnce();
}
if (!nodeStack.isEmpty())
{
root = nodeStack.back();
nodeStack.pop_back();
}
else
{
root = nullptr;
emit errorOccurred(QString("表达式为空")); //表达式为空
}
}
void TreeBackend::reduceOnce()
{
if (opStack.isEmpty() || nodeStack.size() < 2)
return;
QChar op = opStack.back();
opStack.pop_back();
treeNode *right = nodeStack.back();
nodeStack.pop_back();
treeNode *left = nodeStack.back();
nodeStack.pop_back();
treeNode *parent = new treeNode();
parent->type = OP;
parent->v.op = op.toLatin1(); // 此处是QChar转char,我不知道原理
parent->left = left;
parent->right = right;
nodeStack.push_back(parent);
}
int TreeBackend::precedence(QChar op)
{
if (op == '+' || op == '-')
return 1;
if (op == '*' || op == '/')
return 2;
return 0;
}
double TreeBackend::evaluate(treeNode *node)
{
if (node->type == NUM)
{
return node->v.num;
}
else
{
double left = evaluate(node->left);
double right = evaluate(node->right);
switch (node->v.op)
{
case '+':
return left + right;
case '-':
return left - right;
case '*':
return left * right;
case '/':
if (right == 0) {
emit errorOccurred(QString("除数不能为0!"));
root = nullptr;
nodes.clear();
lines.clear();
return 0.0; // 或者其他适当的错误处理
}
return left / right;
default:
return 0.0; // TODO 如果出现 x/0的情况呢,抛出异常?
}
}
}
void TreeBackend::putDepth(treeNode *node, int depth)
{ // 赋予深度
if (node == nullptr)
return;
node->depth = depth;
putDepth(node->left, depth + 1);
putDepth(node->right, depth + 1);
}
void TreeBackend::putId(treeNode *node)
{
if (node == nullptr)
return;
putId(node->left);
node->id = idCounter++;
putId(node->right);
}
void TreeBackend::setLocation(treeNode *root, int singleWight, int singleHeight)
{
if (root == nullptr)
return;
int x = (root->id + 1) * singleWight;
int y = (root->depth + 1) * singleHeight;
nodes.append(QVariantMap{{"id", root->id}, {"x", x}, {"y", y}, {"label", root->type == NUM ? QString::number(root->v.num) : QString(root->v.op)}});
setLocation(root->left, singleWight, singleHeight);
setLocation(root->right, singleWight, singleHeight);
}
void TreeBackend::setFromTo(treeNode *root)
{
if (root == nullptr)
return;
treeNode *left = root->left;
treeNode *right = root->right;
if (left)
{
int from = root->id;
int to = left->id;
lines.append(QVariantMap{{"from", from}, {"to", to}});
setFromTo(left);
}
if (right)
{
int from = root->id;
int to = right->id;
lines.append(QVariantMap{{"from", from}, {"to", to}});
setFromTo(right);
}
}
int TreeBackend::getMaxDepth(treeNode *root)
{
if (root == nullptr)
return 0;
return 1 + std::max(getMaxDepth(root->left), getMaxDepth(root->right));
}