01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package enumeration;

public interface Expr {
  void printPostorder();
  int evaluate();
}

class Const implements Expr {
  private final int v;
  public Const(int v) {
    this.v = v;
  }

  public int evaluate() {
    return v;
  }
  public void printPostorder() {
    System.out.print(v + " ");
  }
}

class BinOp implements Expr {
  private final Expr l;
  private final Expr r;
  private final Op op;

  public BinOp(Expr l, Op op, Expr r) {
    if ((l == null) || (op == null) || (r == null)) {
      throw new IllegalArgumentException();
    }
    this.op = op;
    this.l = l;
    this.r = r;
  }

  public int evaluate() {
    return op.eval(l.evaluate(), r.evaluate());
  }
  public void printPostorder() {
    l.printPostorder();
    r.printPostorder();
    System.out.print(op + " ");
  }
}