puts parentheses round every operator and pair of operands". I'm thus assuming the output should look like (1+(2)*3)
.
I don't think this should be the output. I think output should be: (1+(2*3))
For me the easiest way to view this is through object oriented approach.
Let abstract class Node
have abstract method GetExpressionString()
and field Token
.
Let class Operand
inherit from Node
and implement GetExpressionString()
so that it returns Token
. (for example '1'
or '2'
or '3'
).
Let class Operator
inherit from Node
, has fields Left
and Right
of type Node
and implement GetExpressionString()
so that it returns '(' + Left.GetExpressionString() + Token + Right.GetExpressionString() + ')'
. For example if Left = '2'
, Right = '3'
and Token = '*'
, then result is '(2*3)'
.
Then for
expression = new Operator(
Token='+',
Left=new Operand(Token='1'),
Right=new Operator(
Token='*',
Left=new Operand(Token='2'),
Right=new Operand(Token='3')))
a call of expression.GetExpressionString()
returns '(1+(2*3))'
.