Question

In: Computer Science

Arithmetic expressions such as                                 2 * (9 / -3)    

Arithmetic expressions such as

                                2 * (9 / -3)                                                                   

have an inherent tree-like structure. For example, Figure A is a representation of the expression in Equation (1). This kind of tree is called an expression tree.

The terminal nodes (leaves) of an expression tree are the variables or constants in the expression (2, 9, 3). The non-terminal nodes of an expression tree are the operators (*, / and -). Notice that the parentheses which appear in Equation (1) do not appear in the tree. Nevertheless, the tree representation has captured the intent of the parentheses since the subtraction is lower in the tree than the multiplication.



Figure A: Tree representing the expression 2 * (9 / -3).

The common arithmetic operators are either unary or binary. For example, addition, subtraction, multiplication, and division are all binary operations and negation is a unary operation. Therefore, the non-terminal nodes of the corresponding expression trees have either one or two non-empty subtrees. That is, expression trees are usually binary trees.

QUESTIONS:

Create an expression tree program that reads a prefix* arithmetic expression and displays it in a binary tree form. Assume that the expression consists of single-digit, nonnegative integers (‘0’ to ‘9’) and four basic arithmetic operators (‘+’, ‘-‘, ‘*’, and ‘/’). Further, assume that the arithmetic expression is input from the keyboard with all the characters on one line.

Then, using traversal techniques display the arithmetic expression in preorder, inorder and postorder notations. Finally evaluates the expression and output the result. Display suitable messages.

Solutions

Expert Solution

// PLEASE LIKE THE SOLUTION
// FEEL FREE TO DISCUSS IN COMMENT SECTION
// C++ PROGRAM

#include<bits/stdc++.h>
using namespace std;

typedef struct expressionTree{
   char val;
   expressionTree *left, *right;
}Node;

// build tree
char* build(Node** root, char* ch){
   if (*ch == '\0'){
       return NULL;
   }

   while (1){
       char* q = NULL;
       if (*root == NULL){
           // build child
           Node* temp = (Node*)malloc(sizeof(Node));
           temp->val = *ch;
           temp->left = NULL;
           temp->right = NULL;
           *root = temp;
       }
       else{
           // if operand
           if (*ch >='0' && *ch <='9'){
               return ch;
           }
          
           // build left
           q = build(&(*root)->left, ch+1);

           // build right
           q = build(&(*root)->right, q+1);

           return q;
       }
   }
}

void preorder(Node* root){
   if(root == NULL){
       return;
   }
   else{
       cout<<(root->val)<<" ";
       preorder(root->left);
       preorder(root->right);
   }
}

void inorder(Node* root){
   if(root == NULL){
       return;
   }
   else{
       inorder(root->left);
       cout<<(root->val)<<" ";
       inorder(root->right);
   }
}

void postorder(Node* root){
   if(root == NULL){
       return;
   }
   else{
       preorder(root->left);
       preorder(root->right);
       cout<<(root->val)<<" ";
   }
}

// evaluate
double evaluate(char a[]){
   int n=strlen(a);
  
   // stack
   stack<double> st;
   for(int i=n-1;i>=0;i--){
       //cout<<a[i]<< " ";
       if(a[i] >= '0' && a[i] <= '9'){
           st.push(a[i]-'0');
       }
       if(a[i] == '*'){
           double t1 = st.top();
           st.pop();

           double t2 = st.top();
           st.pop();

           double r = t1*t2;
           st.push(r);
       }

       if(a[i] == '/'){
           double t1 = st.top();
           st.pop();

           double t2 = st.top();
           st.pop();

           double r = t1/t2;
           st.push(r);
       }

       if(a[i] == '+'){
           double t1 = st.top();
           st.pop();

           double t2 = st.top();
           st.pop();

           double r = t1+t2;
           st.push(r);
       }

       if(a[i] == '-'){
           double t1 = st.top();
           st.pop();

           double t2 = st.top();
           st.pop();

           double r = t1-t2;
           st.push(r);
       }
      
   }

   return st.top();
}

// Driver program to test above
int main(){
   Node* root = NULL;
   char a[100];
   scanf("%s",a);

   build(&root, a);
   printf("PreOrder = ");
   preorder(root);
   printf("\n");
  
   printf("InOrder = ");
   inorder(root);
   printf("\n");

   printf("PostOrder = ");
   postorder(root);
   printf("\n");

   double re = evaluate(a);
   cout<<"Evaluation = "<<re<<endl;
   return 0;
}

// SAMPLE OUTPUT


Related Solutions

I need to write an interpreter for arithmetic expressions in Python. This program receives an input...
I need to write an interpreter for arithmetic expressions in Python. This program receives an input string with an arithmetic expression and does: 1. prints a ">>>" as if it was a terminal 2. lets us allocate a variable to a a numeric value (as "a = 3") then it stores {'a':3} to a dictionary memory 3. whenever it receives an expression or input, transform it to postfix notation and print it (even when allocating variables) 4. it is able...
Modify the following code to use ONLY pointer arithmetic (no array expressions) and no for loops...
Modify the following code to use ONLY pointer arithmetic (no array expressions) and no for loops to do the same thing this code does. Be sure that you understand how the code works and how the pointer arithmetic relates to the array expression form. Provide liberal comments to explain what your pointer arithmetic is computing. #include <stdlib.h> #include <stdio.h> int main(int argc, char **argv) { int arg_count = 0; for (arg_count = 0; arg_count < argc; arg_count++) printf("%s\n", argv[arg_count]); }
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by...
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees. Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that a given expression could result in one of the...
C++ OOP Make a program to evaluate infix arithmetic expressions containing integer operands and the operators...
C++ OOP Make a program to evaluate infix arithmetic expressions containing integer operands and the operators + (addition), - (subtraction), * (multiplication), / (division) and pairs of parentheses, properly nested. Use the following two-stack algorithm (by E. W. Dijkstra): If the next token in the expression is an integer, push the integer onto the value stack. If the next token in the expression is an operator, If the operator stack is empty or the priority of the operator is greater...
Consider a system which has to accept prefix arithmetic expressions consisting of ‘+’(binary addition) , ‘-‘(binary...
Consider a system which has to accept prefix arithmetic expressions consisting of ‘+’(binary addition) , ‘-‘(binary subtraction), ‘*’(multiplication), ‘~’(unary subtraction), single digit numbers and compute their value. Examples: +12 → 3 ++12 → fail +*123 → 5 *+123 → 9 +123 → fail What parts would be required for such a system? How do these parts relate to the concepts studied? Could you write a program to implement such a system? (Layout of the structure and the logic of the...
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by...
In assignment 1 you had used the data structure called Stack to evaluate arithmetic expressions by first converting the given infixed expressions to postfixed expressions, and then evaluated the post fixed expression. Repeat the exercise for this assignment (assignment 2) by using the data structure called Binary Trees. Your output must display the original expression, the postfixed expression representing the Binary tree, and the evaluated result. Please bear in mind that a given expression could result in one of the...
Write a recursive formula for the arithmetic sequence 0, −1/2 , −1, −3/2 , … , and then find the 31st term.
Write a recursive formula for the arithmetic sequence 0, −1/2 , −1, −3/2 , … , and then find the 31st term.  
For the function ?(?) = 2? 3 + 9? 2 − 108? + 30 find the...
For the function ?(?) = 2? 3 + 9? 2 − 108? + 30 find the following (round to the nearest thousandth if needed): a. Interval(s) where the function is increasing b. Interval(s) where the function is decreasing c. Relative maximum and minimum points (x and y values) d. Inflection point(s) (x and y values) e. Interval(s) where the function is concave up f. Interval(s) where the function is concave down
For the arithmetic progression a1, a2, a3 .......... if a4/a7 = 2/3. Find a6/a8 ?
For the arithmetic progression a1, a2, a3 .......... if a4/a7 = 2/3. Find a6/a8 ?
Evaluate the polynomial y= x^3- 5x^2+ 6x + 0.55 at x=.137. Use 3-digit arithmetic with rounding....
Evaluate the polynomial y= x^3- 5x^2+ 6x + 0.55 at x=.137. Use 3-digit arithmetic with rounding. Evaluate the percent relative error. (b) Repeat (a) but express y as y= ((x- 5)x +6)x + 0.55
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT