#1612
Medium Algorithms Check if two expression trees are equivalent
Hash Table Tree Depth-First Search Binary Tree Counting
71.8% acceptance
Mar 31, 2026
146
24
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.
Solution
C++
Time O(n)
Space O(1)
/**
* Definition for a binary tree node.
* struct Node {
* char val;
* Node *left;
* Node *right;
* Node() : val(' '), left(nullptr), right(nullptr) {}
* Node(char x) : val(x), left(nullptr), right(nullptr) {}
* Node(char x, Node *left, Node *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
bool checkEquivalence(Node* root1, Node* root2) {
vector<int> cnt(26, 0);
count(root1, cnt, 1);
count(root2, cnt, -1);
for (int c : cnt) if (c != 0) return false;
return true;
}
private:
void count(Node* node, vector<int>& cnt, int sign) {
if (!node) return;
if (node->val != '+') {
cnt[node->val - 'a'] += sign;
}
count(node->left, cnt, sign);
count(node->right, cnt, sign);
}
};