709. Check If Two Expression Trees are Equivalent

You are given two binary trees representing mathematical expressions. Each tree node contains either a lowercase English letter ('a' to 'z') or the character +.

Two binary expression trees are equivalent if they evaluate to the same value, regardless of what the variables are set to.

The task is to check whether the two expression trees are equivalent.

Example 1:

Input: root1 = ["x"], root2 = ["x"]

Output: true

Explanation:

Both trees contain a single node with the value x.

Example 2:

Input: root1 = ["+", "a", "+", "null", "null", "b", "c"], root2 = ["+", "+", "a", "b", "c"]

Output: true

Explanation:

The expressions a + (b + c) and (b + c) + a are equivalent due to the associative property of addition.

Now Your Turn!

Pick the correct output for the given input

Input: root1 = ["+", "a", "+", "null", "null", "b", "c"], root2 = ["+", "+", "a", "b", "d"]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in both trees are equal, odd and, in the range [1, 4999].
  • Node.val is '+' or a lower-case English letter.
  • It's guaranteed that the tree given is a valid binary expression tree.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* class TreeNode {
* char data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(char x) : data(x), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
bool checkEquivalence(TreeNode* root1, TreeNode* root2) {
}
};
 
Test Case

Input:

Root1
Root2