VOOZH about

URL: https://www.geeksforgeeks.org/dsa/evaluation-of-expression-tree/

⇱ Evaluation of Expression Tree - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Evaluation of Expression Tree

Last Updated : 10 Mar, 2023

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

👁 pic2

Output:100

Input: Root node of the below tree

👁 pic1

Output: 110

Recommended Practice

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:


Output
60
110

Time Complexity: O(n), as each node is visited once.
Auxiliary Space: O(n)

Comment
Article Tags:
Article Tags: