Compare Expression Trees
Filed under Google
Free read 2 of 3Determine if commutative operators (like addition and multiplication) should evaluate trees like (A + B) and (B + A) as equivalent.
The question
Given the roots of two expression trees, determine if they are structurally equivalent and represent the same mathematical expression.
Constraints
- Nodes can be operators (+, -, *, /) or operands (numbers/variables).
- Tree nodes contain a value and left/right children.
Examples
- Input
- Tree 1: (+ 2 3), Tree 2: (+ 2 3)
- Output
- True
- Why
- Both trees have the same operator and identical left and right subtrees.
Approach
Determine if commutative operators (like addition and multiplication) should evaluate trees like (A + B) and (B + A) as equivalent.
Check if both nodes are null (return True) or if only one is null (return False).
Compare current node values, then recursively check left-to-left and right-to-right subtrees.
Single node trees, unbalanced trees, and trees with different structures.
Tips
- What they are testing: Tests recursive tree traversal and handling commutative properties if applicable.
- Common mistake: Only checking node values without recursively verifying both left and right children.
Related Google questions
Collected from public candidate posts and coding forums. Updated Nov 2026.