【发布时间】:2019-07-25 06:55:54
【问题描述】:
我目前正在尝试找出表达式树的算法。我目前将获得的字符串类似于Hello+12+World 或A2-12-A3-14。字符串中将包含相同的运算符。使用我的算法,目前最后一个操作数没有被放入树中。我在网上查了一下,我很难理解如何让它正常工作。
Stack<BaseNode> TreeStack = new Stack<BaseNode>();
BaseNode temp1 = new BaseNode();
BaseNode temp2 = new BaseNode();
for (int i = 0; i < tree.Length; i++)
{
VariableNode varNode = new VariableNode();
NumericalNode numNode = new NumericalNode();
if (CheckExpressions(tree[i])) // if the character is an operator
{
OperatorNode expression = new OperatorNode(tree[i]);
temp1 = TreeStack.Pop();
if (TreeStack.Count != 0)
{
temp2 = TreeStack.Pop();
}
expression.Right = temp1;
expression.Left = temp2;
TreeStack.Push(expression);
}
else if (!CheckExpressions(tree[i]))
{
if (Char.IsLetter(tree[i]))
{
while (Char.IsLetter(tree[i])) // for the variable node
{
varNode.name += tree[i];
if (i + 1 == tree.Length)
{
break;
}
i++;
}
TreeStack.Push(varNode);
if (i + 1 != tree.Length)
{
i--;
}
}
else if (Char.IsDigit(tree[i])) // for constant value
{
int zero = 0; // for appending the numbers to combine them
while (Char.IsDigit(tree[i]))
{
if (zero == 0)
{
zero = tree[i] - '0';
}
else
{
zero = int.Parse(zero.ToString() + tree[i].ToString());
}
if (i < tree.Length)
{
i++;
}
}
if (i + 1 != tree.Length)
{
i--;
}
numNode.number = zero;
TreeStack.Push(numNode);
}
}
}
【问题讨论】:
-
我想你可以搜索波兰表示法。
标签: c# algorithm tree expression