Compilers
What does the abstract syntax tree for the expression 2 + 3 * 4 look like?
- AThe root is a + node whose right child is a * node representing 3 * 4
- BThe root is a * node whose left child is a + node representing 2 + 3
- CThe five nodes 2, 3, 4, + and * all sit directly under the root
Show answer and explanation
Answer: A. The root is a + node whose right child is a * node representing 3 * 4
Multiplication has higher precedence than addition, so the expression means 2 + (3 * 4). In an AST, operations computed first sit lower, so the root is +, its left child is 2 and its right child is a * node with children 3 and 4. Evaluating bottom-up computes 3 * 4 = 12 first, then 2 + 12 = 14. A * root corresponds to (2 + 3) * 4, and a flat list cannot express evaluation order.
- A. Correct. The higher-precedence * sits lower, and the root is +.
- B. A * root corresponds to (2 + 3) * 4.
- C. A flat arrangement cannot express evaluation order.