Evaluating an arithmetic abstract syntax tree

699 Views Asked by At

This might be very simplistic for this forum (apologies, if so). How does one evaluate the tree below. I am not looking for a solution, just assistance in how to evaluate it:

Abstract syntax tree

I assume I start at the top node, (i.e. add the two node answers together)

  • Left node, right split: $ ( 2 \div 1 ) $ — this needs to get multiplied with next left split.
  • Left node left split, left split, $ 160 \cdot 5 $.
  • Left node right split: $ 160^{676} $ ?
  • Right node left split, left split: $ 145 + 27 $ ?
  • Right node left split right split: ?
  • Right node right split: wheel completely fallen off.

Thanks in advance.

1

There are 1 best solutions below

1
On

The tree doesn't make any sense (assuming that it is an Abstract Syntax Tree). In ASTs, you recursively evaluate the children of a node, which doesn't make much sense here (you cannot say, "What is $ \times 5 $?").

Let me briefly explain why:

  1. In ASTs, the precedence is described in the tree structure, and not their nodes (that is, there is no parathesis node).

  2. The nodes follows some rules, based on their type, for example $ + $ is a binary operation, and thus has exactly two children. Nonetheless, your example contains multiple nodes breaking these rules.

So, in conclusion, the tree is malformed and cannot be evaluated as is.