Fold and Prune an Arithmetic Expression Tree
Trees & GraphsAuto-graded · 15 test casesLast 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):
| Pattern | Simplified form |
|---|---|
x + 0 | x |
0 + x | x |
x - 0 | x |
x * 0 | 0 (a constant-zero leaf) |
0 * x | 0 (a constant-zero leaf) |
x * 1 | x |
1 * x | x |
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-
Nonechildren. - Leaf
"val"is either anint(never abool) 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).
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
Key insight: bottom-up (post-order) traversal
Every simplification rule inspects a node's children. That means a node can only be simplified correctly after its children have already been simplified. A single bottom-up pass is therefore sufficient: by the time we process a node, both children are in their final form, so any cascade — such as (x * 1) + (2 * 3) collapsing first to x + 6 and not requiring a second pass — is handled automatically.
Iterative post-order with an explicit stack
Python's default recursion limit (~1000 frames) would break on a deep or right-skewed tree, so we simulate the recursion with an explicit stack. Each entry is a (node, visited) pair:
- On the first encounter (
visited=False) we push the node again withvisited=True, then push its right and left children (right first so left is processed first). - On the second encounter (
visited=True) both children are already in thesimplifiedmap, so we can evaluate the current node.
We key the map on id(node) — the CPython object identity — to avoid any collision between nodes that happen to hold the same value.
Rule application order
At each internal node we apply rules in this priority:
- Constant folding — both children are constant leaves → evaluate arithmetically.
- Additive identity —
0 + xorx + 0→ return the non-zero child. - Subtractive identity —
x - 0→ return the left child. (0 - xis intentionally left unchanged.) - Multiplicative zero — either child is
0→ return a fresh0leaf. - Multiplicative identity —
1 * xorx * 1→ return the non-one child. - No rule — rebuild the node with the (already simplified) children.
Returning the simplified child directly (rather than copying it) is safe because we never mutate any node.
Constant-leaf detection
Because Python's bool is a subclass of int, the check isinstance(val, int) alone would misclassify True/False. The guard not isinstance(val, bool) prevents that.
Complexity
- Time: O(n), where n is the number of nodes — each node is pushed and popped twice.
- Space: O(n) for the
simplifiedmap plus O(h) for the traversal stack, where h is the tree height (O(n) worst case for a skewed tree, O(log n) for a balanced one).
Reference solution
from typing import Dict
def fold_expression_tree(root: Dict) -> Dict:
if root is None:
return None
simplified = {}
stack = [(root, False)]
while stack:
node, visited = stack.pop()
if not visited:
stack.append((node, True))
if node.get("right") is not None:
stack.append((node["right"], False))
if node.get("left") is not None:
stack.append((node["left"], False))
continue
val = node["val"]
left_child = node.get("left")
right_child = node.get("right")
if left_child is None and right_child is None:
simplified[id(node)] = {"val": val, "left": None, "right": None}
continue
left = simplified[id(left_child)]
right = simplified[id(right_child)]
a, b = left["val"], right["val"]
def is_const(n):
return (
n["left"] is None
and n["right"] is None
and isinstance(n["val"], int)
and not isinstance(n["val"], bool)
)
left_const = is_const(left)
right_const = is_const(right)
if left_const and right_const:
if val == "+":
result = a + b
elif val == "-":
result = a - b
elif val == "*":
result = a * b
else:
raise ValueError(f"Unsupported operator: {val}")
simplified[id(node)] = {"val": result, "left": None, "right": None}
elif val == "+" and left_const and a == 0:
simplified[id(node)] = right
elif val == "+" and right_const and b == 0:
simplified[id(node)] = left
elif val == "-" and right_const and b == 0:
simplified[id(node)] = left
elif val == "*" and (
(left_const and a == 0) or (right_const and b == 0)
):
simplified[id(node)] = {"val": 0, "left": None, "right": None}
elif val == "*" and left_const and a == 1:
simplified[id(node)] = right
elif val == "*" and right_const and b == 1:
simplified[id(node)] = left
else:
simplified[id(node)] = {"val": val, "left": left, "right": right}
return simplified[id(root)]