Wednesday, May 18, 2011

some answers for final

again, link to the final


 2 3 + 4 ×

string Visit(node, priorPrecedence) {
  if node is number
    return number.ToString()
  result = Visit(left, node.precedence) +
           node.Operator +
           Visit(right, node.precedence)
  if node.precedence < priorPrecedence
    result = '(' + result + ')'
  return result
}

// two parts.
//part 1: build the expression tree.

Node buildExpressionTree(string s)
{
Stack<Node> St = new Stack<Node>();
for (char c : s)
{
switch(c)
{
case '+':
case '-':
case 'x':
case '/':
Node rhs = St.pop();
Node lhs = St.pop();
Node n = new Node(c);
n.right = rhs;
n.left = lhs;
St.push(n);
break;
default: // a digit
Node n = new Node(Integer.parse(c.toString()));
St.push(n);
}
}
return St.pop();
}

// part 2
// printing out the expression tree InOrder
void InOrder(Node n)
{
if (n == null)
return;
System.out.print("(");
InOrder(n.left);
System.out.print(" " + n.element + " ");
InOrder(n.right);
System.out.print(")");
}

3 comments:

  1. Was this for #4 or #5? If the former could you please explain #5?

    ReplyDelete
  2. this was for #5.
    for #4, we would just actually perform the evaluation of the expression and push the RESULT onto the stack. since this is #5, we are instead each time constructing a tree and pushing the resulting TREE onto the stack.

    --josh

    ReplyDelete
  3. for (char c : s)
    should be
    for (char c : s.toCharArray())

    Node n = new Node(Integer.parse(c.toString()));
    may be changed to
    Node n = new Node(Character.getNumericValue(c));

    ReplyDelete