KatInterview

Fold and Prune an Arithmetic Expression Tree

Trees & GraphsAuto-graded · 15 test cases
MediumAuto-gradedTrees & Graphstreesrecursionast

Last updated

Tests recursive AST traversal by simplifying an arithmetic expression tree through constant folding and algebraic identity rules, including cascading rewrites.

Fold and Prune an Arithmetic Expression Tree

You are given the root of a binary expression tree representing an arithmetic expression. Each internal node stores a binary operator and has exactly two children; each leaf stores either an integer constant or a variable name (a string).

Nodes are represented as plain dictionaries with this shape:

{
    "val":   "+",   # operator for internal nodes; int or str for leaves
    "left":  ...,   # left child dict, or None for leaves
    "right": ...    # right child dict, or None for leaves
}

Write a function that returns a new, equivalent expression tree with every possible simplification applied. The original tree must not be modified.

Simplification rules

Apply both of the following rule families wherever they are applicable, including in situations where one simplification exposes another:

Constant folding — if both children of an operator node are integer constants, replace the entire node with a single constant leaf holding the computed result.

Algebraic identities — replace operator nodes that match any of the patterns below with the indicated result, where x stands for any subtree (not necessarily a constant):

PatternSimplified form
x + 0x
0 + xx
x - 0x
x * 00 (a constant-zero leaf)
0 * x0 (a constant-zero leaf)
x * 1x
1 * xx

Note that subtraction is not commutative: 0 - x does not simplify to x.

Rules are checked in the order listed above; constant folding takes priority over identity rules when both could apply to the same node.

Only the operators +, -, and * appear in the input. Boolean values will never appear as constants.

Constraints

  • The tree contains at least one node.
  • Every internal node has exactly two non-None children.
  • Leaf "val" is either an int (never a bool) or a non-empty string naming a variable.
  • Internal node "val" is one of "+", "-", "*".
  • The tree may be arbitrarily deep.
  • Return a freshly constructed tree; do not mutate the input.

Examples

Example 1

Input: fold_expression_tree({'val': '+', 'left': {'val': '*', 'left': {'val': 'x', 'left': None, 'right': None}, 'right': {'val': 1, 'left': None, 'right': None}}, 'right': {'val': '*', 'left': {'val': 2, 'left': None, 'right': None}, 'right': {'val': 3, 'left': None, 'right': None}}})

Output: {'val': '+', 'left': {'val': 'x', 'left': None, 'right': None}, 'right': {'val': 6, 'left': None, 'right': None}}

Example 2

Input: fold_expression_tree({'val': '*', 'left': {'val': '+', 'left': {'val': 'y', 'left': None, 'right': None}, 'right': {'val': 0, 'left': None, 'right': None}}, 'right': {'val': '-', 'left': {'val': 4, 'left': None, 'right': None}, 'right': {'val': 4, 'left': None, 'right': None}}})

Output: {'val': 0, 'left': None, 'right': None}

Hints

Hint 1

Process children before their parent so that a simplified child can immediately trigger a further simplification at the parent level — a single bottom-up pass is sufficient.

Hint 2

An iterative post-order traversal with an explicit stack avoids Python's recursion depth limit on deep or skewed trees; store each node's simplified result keyed by the original node's identity.

Hint 3

Before testing any identity rule, check whether a child subtree is a constant leaf by verifying that both its left and right pointers are None and that its val is an int (and not a bool).