All pastes #364311 Raw Edit

Miscellany

public text v1 · immutable
#364311 ·published 2007-02-20 02:30 UTC
rendered paste body
public class test
{
  public static int eval(ExpressionTree root)
  {
    if(!root.isOper())
      return Integer.valueOf(""+root.getValue());
    if((""+root.getValue()).equals("+"))
      return eval(root.getLeft()) + eval(root.getRight());
    if((""+root.getValue()).equals("*"))
      return eval(root.getLeft()) * eval(root.getRight());
    return 0;
  }
  public static String toInfixNotation(ExpressionTree root)
  {
    if(!root.isOper())
      return ""+root.getValue();
    return "(" + toInfixNotation(root.getLeft()) + " " +
           root.getValue() + " " + toInfixNotation(root.getRight()) + ")";
  }
  public static void main()
  {
    ExpressionTree n5 = new ExpressionTree("4");
    ExpressionTree n4 = new ExpressionTree("3");
    ExpressionTree n3 = new ExpressionTree("*",n5,n4);
    ExpressionTree n2 = new ExpressionTree("10");
    ExpressionTree n1 = new ExpressionTree("+",n2,n3);
    System.out.println(eval(n1));
    System.out.println(toInfixNotation(n1));
  }
}
public class ExpressionTree extends TreeNode
{
  public ExpressionTree()
  {
    super(null);
  }
  public ExpressionTree(Object e)
  {
    super(e);
  }
  public ExpressionTree(Object e, ExpressionTree l, ExpressionTree r)
  {
    super(e,l,r);
  }
  public boolean isOper()
  {
    return (""+getValue()).equals("+") ||
           (""+getValue()).equals("*");
  }
  public ExpressionTree getLeft()
  {
    return (ExpressionTree)super.getLeft();
  }
  public ExpressionTree getRight()
  {
    return (ExpressionTree)super.getRight();
  }
}