Drawing ASTs for expressions: Correct Solution
For each of the Java expressions below:
- Draw an AST for the expression.
- Show how the expression evaluates at each node in the tree.
Be sure that your tree accurately reflects how Java would evaluate the expression.
Part 1
Draw the AST and evaluation results for the following expression:
1 * 3 - 2 % 3 - 5
Solution
Things to double-check in your solution:
- Do you have the left and right branches on the correct side?
- Did you indicate the difference between ints and floating point values?
Part 2
Given the following variables:
boolean a = true;
double ga = 4.0;
...draw the AST and evaluation results for the following expression:
!a || 0 >= 0 || 0 >= ga || 8 < 9
Solution
Things to double-check in your solution:
- Does your tree correctly reflect the precedence of && and ||?
- Did you correctly show short-circuiting? (That is when the right branch of && or || is never evaluated because the left branch already determines the answer.)
Part 3
Draw the AST and evaluation results for the following expression:
0 + (1 + 2 + 3) + 4 + "5"
Solution
Things to double-check in your solution:
- Did you indicate the distinction between ints and Strings?
- Are your left/right branches correct?
Related puzzles: