[LeetCode] Check If Two Expression Trees are Equivalent

1612. Check If Two Expression Trees are Equivalent

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
/**
* 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 {
unordered_map<char, int> freq;
void dfs(Node* node, int v) {
if(!node) return;
if(isalpha(node->val)) {
freq[node->val] += v;
} else {
dfs(node->left, v);
dfs(node->right, v);
}
}
public:
bool checkEquivalence(Node* root1, Node* root2) {
dfs(root1, 1);
dfs(root2, -1);
for(auto [k, v] : freq) if(v) return false;
return true;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/08/PS/LeetCode/check-if-two-expression-trees-are-equivalent/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.