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 Treeoutput:100input:root node of the below treeoutput:110
We strongly recommend minimize your browser and try this yourself first.
As all of the operators in the tree is binary hence each node would 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 nod ES represent the operators.
To evaluate the syntax tree, a recursive approach can be followed.
Algorithm:let t be the syntax Treeif t was not null then If t.info are operand then Return t.info else< C6/>a = Solve (t.left) B = Solve (t.right) return A operator B where operator is the info contained in T
The time complexity would was O (n), as each node is visited once. Below is a C + + program for the same:
1#include <iostream>2#include <cstdlib>3 using namespacestd;4 5typedefstructnode{6 strings;7Node *Left ;8Node *Right ;9Nodestringx): S (x), left (null), right (null) {}Ten }node; One A //Utility function to return the integer value - //of a given string - intToInt (strings) { the intLen =s.length (); - intnum =0; - for(inti =0; i < Len; i++){ -num = num *Ten+ (s[i]-'0'); + } - returnnum; + } A at //Check which operator to apply - intCalculateConst Char*c,intLval,intrval) { - intans; - Switch(*c) { - Case '+': ans = lval + rval; Break; - Case '-': ans = lval-rval; Break; in Case '*': ans = lval * rval; Break; - Case '/': ans = lval/rval; Break; to } + returnans; - } the * //This function receives a node of the syntax tree $ //and recursively evaluates itPanax Notoginseng intEval (Node *root) { - //Empty Tree the if(Root = =NULL) + return 0; A //leaf node i.e, an integer the if(Root->left = = NULL && Root->right = =NULL) + returnToInt (root->s); - //Evaluate left subtree $ intLval = eval (root->Left ); $ //Evaluate Right subtree - intRval = eval (root->Right ); - returnCalculate ((root->s). C_str (), lval, rval); the } - Wuyi intMain () the { - //Create a syntax tree WuNode *root =NewNode"+"); -Root->left =NewNode"*"); AboutRoot->left->left =NewNode"5"); $Root->left->right =NewNode"4"); -Root->right =NewNode"-"); -Root->right->left =NewNode" -"); -Root->right->right =NewNode" -"); Acout << eval (root) <<Endl; + the Delete(root); - $Root =NewNode"+"); theRoot->left =NewNode"*"); theRoot->left->left =NewNode"5"); theRoot->left->right =NewNode"4"); theRoot->right =NewNode"-"); -Root->right->left =NewNode" -"); inRoot->right->right =NewNode"/"); theRoot->right->right->left =NewNode" -"); theRoot->right->right->right =NewNode"2"); About thecout <<eval (root); theSystem"Pause"); the return 0; +}
100
110
Reference: http://www.geeksforgeeks.org/evaluation-of-expression-tree/
Evaluation of Expression Tree