Evaluation of Expression Tree

Evaluation of Expression Tree

Given a simple expression tree, consisting of basic binary operators i.e., + , – ,* and / and some integers, evaluate the expression tree.

Examples:

Input :
Root node of the below tree
Evaluation of Expression Tree Output :
100 Input :
Root node of the below tree
Evaluation of Expression Tree Output :
110

We strongly recommend you to minimize your browser and try this yourself first.

As all the operators in the tree are binary hence each node will have either 0 or 2 children. As it can be inferred from the examples above , the integer values would appear at the leaf nodes , while the interior nodes represent the operators.
To evaluate the syntax tree , a recursive approach can be followed .

Algorithm :
Let t be the syntax tree
If t is not null then
If t.info is operand then
Return t.info
Else
A = solve(t.left)
B = solve(t.right)
return A operator B
where operator is the info contained in t

The time complexity would be O(n), as each node is visited once. Below is a C++ program for the same:

 #include <iostream>
#include <cstdlib>
using namespace std; typedef struct node{
string s;
node *left;
node *right;
node(string x): s(x), left(NULL), right(NULL){}
}Node; // Utility function to return the integer value
// of a given string
int toInt(string s){
int len = s.length();
int num = ;
for(int i = ; i < len; i++){
num = num * + (s[i]-'');
}
return num;
} // Check which operator to apply
int calculate(const char *c, int lval, int rval){
int ans;
switch(*c){
case '+': ans = lval + rval; break;
case '-': ans = lval - rval; break;
case '*': ans = lval * rval; break;
case '/': ans = lval / rval; break;
}
return ans;
} // This function receives a node of the syntax tree
// and recursively evaluates it
int eval(Node *root){
// empty tree
if(root == NULL)
return ;
// leaf node i.e, an integer
if(root->left == NULL && root->right == NULL)
return toInt(root->s);
// Evaluate left subtree
int lval = eval(root->left);
// Evaluate right subtree
int rval = eval(root->right);
return calculate((root->s).c_str(), lval, rval);
} int main()
{
// create a syntax tree
node *root = new node("+");
root->left = new node("*");
root->left->left = new node("");
root->left->right = new node("");
root->right = new node("-");
root->right->left = new node("");
root->right->right = new node("");
cout << eval(root) << endl; delete(root); root = new node("+");
root->left = new node("*");
root->left->left = new node("");
root->left->right = new node("");
root->right = new node("-");
root->right->left = new node("");
root->right->right = new node("/");
root->right->right->left = new node("");
root->right->right->right = new node(""); cout << eval(root);
system("pause");
return ;
}

100

110

参考:http://www.geeksforgeeks.org/evaluation-of-expression-tree/

上一篇:C#中decimal ,double,float的区别


下一篇:decimal与 float的区别