简体   繁体   中英

Logic behind recursively building a binary expression tree from a stack

I am building binary expression tree that uses operators, variables, and integers.

The user enters the expression and we tokenize it based on spaces and place each token into the stack.

For example,

User enters : ab +

Our stack becomes Stack = ["+", "b", "a"]

I have a function that creates an expression node.

xpNode* createExpressionNode(char token[], xpNode *left, xpNode *right)

This is where I am struggling to grasp the recursive concept, this is the pseudocode I've come up with to help me understand how this should work. I would appreciate it if someone could take a look and shed some light on what to do when the stack is empty, and if there's anything else wrong here.

xpNode* createTree(Stack *stack){
{
   xpNode *node;
   get the top of the stack and store it in data
   pop the stack
   if the stack is empty, do something //im lost on what to do here
   if the top is an integer, node = createExpressionNode(data, NULL NULL) //the left and right arguments will always be NULL because integer's wont have any children
   if the top is a variable, node = createExpressionNode(data, NULL, NULL) //the left and right arguments will always be NULL because variables wont have any children
   if the top is an operator, node = createExpressionNode(data, createTree(stack), createTree(stack)) //Operators have children so we need to recursively get them

   return node
}

The result of the input: ab + should be a tree that looks like:

     +
    / \
   a   b 

Isn't the point of this representation that you don't need recursion? The logic should just be like

stack = an empty stack;
while (token = read_next_token()) {
  if (token is a term) {
    push(stack, createTerm(token));
  } else if (token is a unary operator) {
    push(stack, createUnOp(token, pop(stack)));
  } else if (token is a binary operator) {
    node *left, *right;
    left = pop(stack);
    right = pop(stack);
    push(stack, createBinOp(token, left, right));
  } else {
    error("unrecognized input");
  }
}

At the end of input, there should be one element on the stack, which is a tree representing the whole expression. If there's more than one element on the stack at the end, then the input was malformed. If at any point you tried to pop the stack when it was empty, the input was malformed.

If the stack is empty there, then there was an error in the input format. For example, if the stack is [+ * 2 3] , you can't build a tree - one more value is needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM