2
我有一点问题。我试图给二叉树添加一个数学表达式,但我无法理解该算法。那就是:二进制表达式树C++
If the current token is a '(':
Add a new node as the left child of the current node, and
descend to the left child.
If the current token is in the list ['+','-','/','*']:
Set the root value of the current node to the operator represented by the current token.
Add a new node as the right child of the current node and descend to the right child.
If the current token is a number:
Set the root value of the current node to the number and return to the parent.
If the current token is a ')':
go to the parent of the current node.
和我迄今所取得的代码:
template<class T>
void Tree<T>::Expr(Node<T> *node, char expr[], int &i)
{
i++;
T x = expr[i];
if(x == '(')
{
node = node->Left;
node = new Node<T>;
node->Left = NULL;
node->Right = NULL;
Expr(node, expr, i);
}
if(x == '+' || x == '-' || x == '*' || x == '/')
{
node->data = x;
node = node->Right;
node = new Node<T>;
node->Left = NULL;
node->Right = NULL;
Expr(node, expr, i);
}
if(x >= '0' && x <= '9')
{
node->data = x;
return;
}
if(x == ')') return;
}
我知道这是一个很大的混乱,但我不能认识到如何实现它。有人可以向我解释算法或给我一个C++代码或更好解释算法的源代码吗?
P.S.下面是我写的新代码,但它仅适用于这样的表达式:(5 + 2)
template<class T>
void Tree<T>::Expr(Node<T> *&node, char expr[], int &i)
{
i++;
if(i >= strlen(expr)) return;
char x = expr[i];
node = new Node<T>;
node->Left = NULL;
node->Right = NULL;
if(x == '(')
{
Expr(node->Left, expr, i);
i++;
x = expr[i];
}
if(x >= '0' && x <= '9')
{
node->data = x;
return;
}
if(x == '+' || x == '-' || x == '*' || x == '/')
{
node->data = x;
Expr(node->Right, expr, i);
}
if(x == ')') return;
}
什么这个代码有问题,你究竟有什么不明白 - 我没有得到你。 –
很明显,代码没有遵循该算法。 我无法理解算法是如何工作的。例如,如果令牌是'('我去了当前节点的左边子节点,那么可以说表达式中的下一个令牌是一个数字,我将这个数字添加到当前节点,我必须回去。我可以回到父母身边吗?我会回到第13行,程序将结束。我应该使用什么样的结构? –