Thursday, August 18, 2016

get string for binary expression tree

   +
 *   7
2 3
= "2*3+7"

   *
 +   7
2 3
= "(2+3)*7"

   /
 *   /
2 3 6 2
= "2*3/6/2"
inode:
    text(putbrackets)
valueNode: inode
    value
    text(putbrackets = true):
        return value.tostring()
operandHighPrecedenceNode: inode
    inode left
    inode right
    operand
    text(putbrackets = true):
        if left == null || right == null || operand == null:
            throw
        return left.text() + operand + right.text()
operandLowPrecedenceNode: operandHighPrecedenceNode
    text(putbrackets = true):
        return putbrackets ? "(" + base.text() + ")" : base.text()

(root):
    if root == null:
        throw
    return root.text(false)
[Hat tip to LW]

No comments:

Post a Comment