LOGBOOK

HELP

Quiz Entry - updated: 2026.09.29

How is a fully parenthesised arithmetic expression printed from its expression tree?

With a specialised inorder traversal: print "(" before traversing a node's left subtree, print the node's operator or operand when visiting it, and print ")" after traversing its right subtree. The tree for $((2 × (a − 1)) + (3 × b))$ prints exactly that string.

The expression tree for ((2 × (a − 1)) + (3 × b))

* Operators are internal nodes, operands are leaves; inorder puts each operator between its operands. *

In an expression tree, every internal node is an operator and every leaf an operand. The operator's left and right subtrees are its two operands, so the tree is a proper binary tree.

Algorithm printExpression(v)
  if hasLeft(v)
    print("(")
    printExpression(left(v))
  print(v.element())
  if hasRight(v)
    printExpression(right(v))
    print(")")

Inorder is the natural choice because normal (infix) notation writes the operator between its operands, which is exactly where inorder visits it. The parentheses restore what the tree encodes structurally but a flat string loses: which operator applies to which operands. Only internal nodes produce parentheses, since only they have children, so leaves print bare.

Tip: the same tree read in preorder gives prefix (Polish) notation, + × 2 − a 1 × 3 b, and in postorder gives postfix (reverse Polish) notation, 2 a 1 − × 3 b × +. Neither needs parentheses.

Go deeper:

From Quiz: ADS / Trees: Structure, Storage and Traversals | Updated: Sep 29, 2026