Expression Tree

PROBLEM :

Given a simple expression tree, which is also a full binary tree consisting of basic binary operators i.e., + , – ,* and / and some integers, Your task is to evaluate the expression tree. You need to complete the function evalTree which takes the root of the tree as its only argument and returns an integer denoting the result obtained by simplifying the expression tree.

Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. Each test case contains an integer N denoting the no of nodes. Then in the next line are N space separated values of the nodes of the Binary tree filled in continous way from the left to the right.

Output:
For each test case output will be the result obtained by simplifying the expression tree.

Constraints:
1<=T<=100
2<=N<=50

Example(To be used only for expected Output):

Input:
2
7
+ * - 5 4 100 20
3
- 4 7

Output:
100
-3

Explanation:
For the first test case
the tree will look like



On simplification gives ((5*4) + (100-20)) = 100 .
For sec test case
the tree will look like
      -
    /   \
  4     7
On simplification gives  4 - 7 =  -3


--------------------------------------------------------------------------------
SIMPLE c++ IMPLEMENTATION :
--------------------------------------------------------------------------------

/*The structure of node is as follows

struct node{
string data;
node *left;
node *right;
};
*/

/*You are required to complete below method */

int calculate(int ,int ,string ) ;
int evalTree(node* root)
{
    if(root==NULL)
        return 0 ;
       
    if(root->left==NULL&&root->right==NULL)
        return stoi(root->data) ;
       
    int lval=evalTree(root->left) ;
    int rval=evalTree(root->right) ;
   
    return calculate(lval,rval,root->data) ;
}


int calculate(int a,int b,string op)
{
    if(op=="+")
        return a+b ;
    else if(op=="-")
        return a-b ;
    else if(op=="*")
        return a*b ;
    else
        return a/b ;
}

---------------------------------------------------------------------------------

Comments

Popular posts from this blog

Count ways to N'th Stair(Order does not matter)

Replace all ‘0’ with ‘5’ in an input Integer

Chocolate Distribution Problem

Remove characters from the first string which are present in the second string

Primality Test ( CodeChef Problem code: PRB01 )