![]() |
VOOZH | about |
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
Output:100
Input: Root node of the below tree
Output: 110
Approach: The approach to solve this problem is based on following observation:
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 can do inorder traversal of the binary tree and evaluate the expression as we move ahead.
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
Below is the implementation of the above approach:
60 110
Time Complexity: O(n), as each node is visited once.
Auxiliary Space: O(n)