Monday, January 25, 2010

Given an expression tree, evaluate the expression and obtain a paranthesized form of the expression.

The code below prints the paranthesized form of a tree.


print_infix_exp(node * root)
{
   if(root)
   {
      printf("(");
      infix_exp(root->left);
      printf(root->data);
      infix_exp(root->right);
      printf(")");
   }
}

Creating a binary tree for a postfix expression

node *create_tree(char postfix[])
{
   node *temp, *st[100];
   int i,k;
   char symbol;

   for(i=k=0; (symbol = postfix[i])!='\0'; i++)
   {
        temp = (node *) malloc(sizeof(struct node));//temp = getnode();
        temp->value = symbol;
        temp->left = temp->right = NULL;

        if(isalnum(symbol))
              st[k++] = temp;
        else
        {
              temp->right = st[--k];
              temp->left  = st[--k];
              st[k++]     = temp;
        }
   }
   return(st[--k]);
}


Evaluate a tree


float eval(mynode *root)
{
   float num;

   switch(root->value)
   {
        case '+' : return(eval(root->left) + eval(root->right)); break;
        case '-' : return(eval(root->left) - eval(root->right)); break;
        case '/' : return(eval(root->left) / eval(root->right)); break;
        case '*' : return(eval(root->left) * eval(root->right)); break;
        case '$' : return(eval(root->left) $ eval(root->right)); break;
        default  : if(isalpha(root->value))
                   {
                      printf("%c = ", root->value);
                      scanf("%f", &num);
                      return(num);
                   }
                   else
                   {
                      return(root->value - '0');
                   }

   }
}

0 comments:

Post a Comment