Given a full binary expression tree consisting of basic binary operators (+, - , *, /) and some integers. Evaluate the value of expression tree and return.
Using Inorder Traversal : O(n) Time and O(h) Space Complexity
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, all the integer values would appear at the leaf nodes, while the interior nodes represent the operators. Therefore we do inorder traversal of the binary tree and evaluate the expression as we move upward in the tree.
Algorithm: Evaluate Expression Tree
If the tree is empty (root == NULL), return 0.
If the current node is a leaf node (operand), convert its value to an integer and return it.
Recursively evaluate the left and right subtrees and store the result in l_val and r_val respectively.
Check the operator stored at the current node (+, -, *, /).
Apply the operator on l_val and r_val, and return the computed result.
C++
#include<iostream>#include<string>usingnamespacestd;/* Definition for Node */classNode{public:stringdata;Node*left;Node*right;Node(stringval){data=val;left=right=nullptr;}};intevalTree(Node*root){// Empty treeif(!root)return0;// Leaf node (operand)if(!root->left&&!root->right)returnstoi(root->data);// Evaluate left and right subtreesintl_val=evalTree(root->left);intr_val=evalTree(root->right);// Apply operatorif(root->data=="+")returnl_val+r_val;if(root->data=="-")returnl_val-r_val;if(root->data=="*")returnl_val*r_val;returnl_val/r_val;}intmain(){/* + / \ * - / \ / \ 5 4 100 20 Expression: (5 * 4) + (100 - 20) Result = 100 */Node*root=newNode("+");root->left=newNode("*");root->right=newNode("-");root->left->left=newNode("5");root->left->right=newNode("4");root->right->left=newNode("100");root->right->right=newNode("20");cout<<evalTree(root)<<endl;return0;}
Java
importjava.util.*;/* Definition for Node */classNode{Stringdata;Nodeleft;Noderight;Node(Stringval){data=val;left=right=null;}}publicclassGFG{staticintevalTree(Noderoot){// Empty treeif(root==null)return0;// Leaf node (operand)if(root.left==null&&root.right==null)returnInteger.parseInt(root.data);// Evaluate left and right subtreesintl_val=evalTree(root.left);intr_val=evalTree(root.right);// Apply operatorif(root.data.equals("+"))returnl_val+r_val;if(root.data.equals("-"))returnl_val-r_val;if(root.data.equals("*"))returnl_val*r_val;returnl_val/r_val;}publicstaticvoidmain(String[]args){/* + / \ * - / \ / \ 5 4 100 20 Expression: (5 * 4) + (100 - 20) Result = 100 */Noderoot=newNode("+");root.left=newNode("*");root.right=newNode("-");root.left.left=newNode("5");root.left.right=newNode("4");root.right.left=newNode("100");root.right.right=newNode("20");System.out.println(evalTree(root));}}
Python
# Definition for NodeclassNode:def__init__(self,val):self.data=valself.left=Noneself.right=NonedefevalTree(root):# Empty treeifnotroot:return0# Leaf node (operand)ifnotroot.leftandnotroot.right:returnint(root.data)# Evaluate left and right subtreesl_val=evalTree(root.left)r_val=evalTree(root.right)# Apply operatorifroot.data=="+":returnl_val+r_valifroot.data=="-":returnl_val-r_valifroot.data=="*":returnl_val*r_valreturnint(l_val/r_val)# Driver Codeif__name__=="__main__":""" + / \ * - / \ / \ 5 4 100 20 Expression: (5 * 4) + (100 - 20) Result = 100 """root=Node("+")root.left=Node("*")root.right=Node("-")root.left.left=Node("5")root.left.right=Node("4")root.right.left=Node("100")root.right.right=Node("20")print(evalTree(root))
C#
usingSystem;/* Definition for Node */classNode{publicstringdata;publicNodeleft;publicNoderight;publicNode(stringval){data=val;left=right=null;}}classGFG{staticintevalTree(Noderoot){// Empty treeif(root==null)return0;// Leaf node (operand)if(root.left==null&&root.right==null)returnint.Parse(root.data);// Evaluate left and right subtreesintl_val=evalTree(root.left);intr_val=evalTree(root.right);// Apply operatorif(root.data=="+")returnl_val+r_val;if(root.data=="-")returnl_val-r_val;if(root.data=="*")returnl_val*r_val;returnl_val/r_val;}staticvoidMain(){/* + / \ * - / \ / \ 5 4 100 20 Expression: (5 * 4) + (100 - 20) Result = 100 */Noderoot=newNode("+");root.left=newNode("*");root.right=newNode("-");root.left.left=newNode("5");root.left.right=newNode("4");root.right.left=newNode("100");root.right.right=newNode("20");Console.WriteLine(evalTree(root));}}
JavaScript
/* Definition for Node */classNode{constructor(val){this.data=val;this.left=null;this.right=null;}}functionevalTree(root){// Empty treeif(root===null){return0;}// Leaf node (operand)if(root.left===null&&root.right===null){returnNumber(root.data);}// Evaluate left and right subtreesletlVal=evalTree(root.left);letrVal=evalTree(root.right);letres;// Apply operatorif(root.data==="+"){res=lVal+rVal;}elseif(root.data==="-"){res=lVal-rVal;}elseif(root.data==="*"){res=lVal*rVal;}else{// C++ integer division truncates towards zero.// Math.trunc() provides the same behavior in// JavaScript.res=Math.trunc(lVal/rVal);}// JavaScript may produce -0 (e.g. Math.trunc(-1 / 2)).// Convert it to 0 so that the output matches C++.returnObject.is(res,-0)?0:res;}// Driver Code/* + / \ * - / \ / \ 5 4 100 20 Expression: (5 * 4) + (100 - 20) Result = 100*/letroot=newNode("+");root.left=newNode("*");root.right=newNode("-");root.left.left=newNode("5");root.left.right=newNode("4");root.right.left=newNode("100");root.right.right=newNode("20");console.log(evalTree(root));