Evaluate a Binary Expression Tree
Evaluate a given binary expression tree representing algebraic expressions.
A binary expression tree is a binary tree, where the operators are stored in the tree’s internal nodes, and the leaves contain constants.
Assume that each node of the binary expression tree has zero or two children. The supported operators are +(addition), −(subtraction), *(multiplication), ÷(division) and ^(exponentiation).
For example, the value of the following expression tree is 28:

We can evaluate an expression tree by applying the operator at the root to values obtained by recursively evaluating left and right subtrees. This can be easily done by traversing the expression tree using postorder traversal. The algorithm can be implemented as follows in C++, Java, and Python:
C++
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
#include <iostream> #include <string> using namespace std; // Data structure to store a binary tree node struct Node { string val; Node *left, *right; Node(string val) { this->val = val; this->left = this->right = nullptr; } }; // Utility function to check if a given node is a leaf node bool isLeaf(Node* node) { return node->left == nullptr && node->right == nullptr; } // Function to apply an operator 'op' to values 'x' and 'y' and return the result double process(string op, double x, double y) { if (op == "+") { return x + y; } if (op == "-") { return x - y; } if (op == "*") { return x * y; } if (op == "/") { return x / y; } return 0; } // Recursive function to evaluate a binary expression tree double evaluate(Node* root) { // base case: invalid input if (root == nullptr) { return 0; } // the leaves of a binary expression tree are operands if (isLeaf(root)) { return stod(root->val); } // recursively evaluate the left and right subtree double x = evaluate(root->left); double y = evaluate(root->right); // apply the operator at the root to the values obtained in the previous step return process(root->val, x, y); } int main() { Node* root = new Node("+"); root->left = new Node("*"); root->right = new Node("/"); root->left->left = new Node("-"); root->left->right = new Node("5"); root->right->left = new Node("21"); root->right->right = new Node("7"); root->left->left->left = new Node("10"); root->left->left->right = new Node("5"); cout << "The value of the expression tree is " << evaluate(root) << endl; return 0; } |
Output:
The value of the expression tree is 28
Java
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
// Data structure to store a binary tree node class Node { String val; Node left, right; Node(String val) { this.val = val; this.left = this.right = null; } } class Main { // Utility function to check if a given node is a leaf node public static boolean isLeaf(Node node) { return node.left == null && node.right == null; } // Function to apply an operator 'op' to values 'x' and 'y' and return the result public static double process(String op, double x, double y) { if (op.equals("+")) { return x + y; } if (op.equals("-")) { return x - y; } if (op.equals("*")) { return x * y; } if (op.equals("/")) { return x / y; } return 0; } // Recursive function to evaluate a binary expression tree public static double evaluate(Node root) { // base case: invalid input if (root == null) { return 0; } // the leaves of a binary expression tree are operands if (isLeaf(root)) { return Double.valueOf(root.val); } // recursively evaluate the left and right subtree double x = evaluate(root.left); double y = evaluate(root.right); // apply the operator at the root to the values obtained in the previous step return process(root.val, x, y); } public static void main(String[] args) { Node root = new Node("+"); root.left = new Node("*"); root.right = new Node("/"); root.left.left = new Node("-"); root.left.right = new Node("5"); root.right.left = new Node("21"); root.right.right = new Node("7"); root.left.left.left = new Node("10"); root.left.left.right = new Node("5"); System.out.println("The value of the expression tree is " + evaluate(root)); } } |
Output:
The value of the expression tree is 28.0
Python
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# Data structure to store a binary tree node class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right # Utility function to check if a given node is a leaf node def isLeaf(node): return node.left is None and node.right is None # Function to apply an operator 'op' to values 'x' and 'y' and return the result def process(op, x, y): if op == '+': return x + y if op == '-': return x - y if op == '*': return x * y if op == '/': return x / y # Recursive function to evaluate a binary expression tree def evaluate(root): # base case: invalid input if root is None: return 0 # the leaves of a binary expression tree are operands if isLeaf(root): return float(root.val) # recursively evaluate the left and right subtree x = evaluate(root.left) y = evaluate(root.right) # apply the operator at the root to the values obtained in the previous step return process(root.val, x, y) if __name__ == '__main__': root = Node('+') root.left = Node('*') root.right = Node('/') root.left.left = Node('-') root.left.right = Node('5') root.right.left = Node('21') root.right.right = Node('7') root.left.left.left = Node('10') root.left.left.right = Node('5') print('The value of the expression tree is', evaluate(root)) |
Output:
The value of the expression tree is 28.0
The time complexity of the above solution is O(n), where n is the total number of nodes in the expression tree. The auxiliary space required by the program is O(h) for the call stack, where h is the height of the tree.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)