Check If Two Expression Trees are Equivalent - Problem
A binary expression tree is a kind of binary tree used to represent arithmetic expressions. Each node of a binary expression tree has either zero or two children. Leaf nodes (nodes with 0 children) correspond to operands (variables), and internal nodes (nodes with two children) correspond to the operators.
In this problem, we only consider the '+' operator (i.e. addition).
You are given the roots of two binary expression trees, root1 and root2. Return true if the two binary expression trees are equivalent. Otherwise, return false.
Two binary expression trees are equivalent if they evaluate to the same value regardless of what the variables are set to.
Input & Output
Example 1 — Different Structure, Same Expression
$
Input:
root1 = ["+","x","y"], root2 = ["+","y","x"]
›
Output:
true
💡 Note:
Both trees represent x + y and y + x. Since addition is commutative, these expressions are equivalent regardless of variable values.
Example 2 — Different Variables
$
Input:
root1 = ["+","x","x"], root2 = ["+","y","y"]
›
Output:
false
💡 Note:
First tree represents x + x (or 2x) while second represents y + y (or 2y). These are not equivalent since they depend on different variables.
Example 3 — Complex Nested Expression
$
Input:
root1 = ["+",["+","x","y"],"z"], root2 = ["+","z",["+","y","x"]]
›
Output:
true
💡 Note:
Tree 1: (x + y) + z, Tree 2: z + (y + x). Both evaluate to x + y + z due to associativity and commutativity of addition.
Constraints
- The number of nodes in both trees are in the range [1, 4000]
- Node.val.length <= 5
- Node.val consists of digits and lowercase English letters
- It's guaranteed that if a node has 2 children, then it is an operator
- It's guaranteed that if a node has 0 children, then it is an operand
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code