A binary expression tree is a specialized binary tree that represents arithmetic expressions. Think of it as a mathematical formula broken down into a tree structure where:
- Leaf nodes contain variables (like 'a', 'b', 'x')
- Internal nodes contain operators (in this problem, only '+' for addition)
You are given the roots of two binary expression trees, root1 and root2. Your task is to determine if these trees are equivalent - meaning they would evaluate to the same result regardless of what values the variables are assigned.
Example: The expressions a + b and b + a are equivalent due to the commutative property of addition, even though their tree structures might look different.
Return true if the two expression trees are equivalent, false otherwise.
Input & Output
Visualization
Time & Space Complexity
Where n and m are the sizes of the two trees. We visit each node exactly once.
Where h is the maximum height of trees (for recursion) and v is the number of unique variables
Constraints
- The number of nodes in both trees are equal and is in the range [1, 4999].
- Node.val.length == 1
- Node.val is either '+' or a lowercase English letter.
- It's guaranteed that the tree given is a valid binary expression tree.