I am working on converting an expression tree to a format reminiscent of infix notation; I do not evaluate a tree or perform its operations. The tree contains both logical and relational operations, and I would like that during the translation I would like to generate parentheses.
To illustrate this, consider the following far-fetched expression:
a < x & (a < y | a == c) & a != d
If I go through the expression tree created by this expression in order, I will print the next expression, which is incorrect.
a < x & a < y | a == c & a != d
Alternatively, I can traverse again in order, but emit parentheses before and after processing the binary expression. This will result in the next correct expression, but with a few fallback brackets.
(((a < x) & ((a < y) | (a == c))) & (a != d))
Is there an expression tree traversal algorithm that generates expressions with optimal parenthesis?
For reference, here is a snippet of ExpressionVisitor that I use to validate the tree.
class MyVisitor : ExpressionVisitor { protected override Expression VisitBinary(BinaryExpression node) { Console.Write("("); Visit(node.Left); Console.WriteLine(node.NodeType.ToString()); Visit(node.Right); Console.Write(")"); return node; }
Steve guidi
source share