Binärer Ausdrucksbaum C ++
Ich habe ein kleines Problem. Ich versuche, einem Binärbaum einen mathematischen Ausdruck hinzuzufügen, aber ich kann den Algorithmus nicht verstehen. Hier ist es:
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.
und den Code, den ich bisher gemacht habe:
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;
}
Ich weiß, dass es ein großes Durcheinander ist, aber ich weiß nicht, wie ich es umsetzen soll. Kann mir jemand den Algorithmus erklären oder mir eine Quelle mit C ++ - Code oder einen besser erklärten Algorithmus geben?
P.S. Hier ist der neue Code, den ich geschrieben habe, aber er funktioniert nur für Ausdrücke wie: (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;
}