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:

Binary Expression Tree

Practice this problem

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++


Download  Run Code

Output:

The value of the expression tree is 28

Java


Download  Run Code

Output:

The value of the expression tree is 28.0

Python


Download  Run Code

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.