Skip to content

1612. Check If Two Expression Trees are Equivalent 👍

  • Time: $O(n)$
  • Space: $O(h)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class Solution {
 public:
  bool checkEquivalence(Node* root1, Node* root2) {
    vector<int> count(26);
    dfs(root1, count, 1);
    dfs(root2, count, -1);
    return ranges::count_if(count, [](int c) { return c != 0; }) == 0;
  }

 private:
  void dfs(Node* root, vector<int>& count, int add) {
    if (root == nullptr)
      return;
    if ('a' <= root->val && root->val <= 'z')
      count[root->val - 'a'] += add;
    dfs(root->left, count, add);
    dfs(root->right, count, add);
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution {
  public boolean checkEquivalence(Node root1, Node root2) {
    int[] count = new int[26];
    dfs(root1, count, 1);
    dfs(root2, count, -1);
    return Arrays.stream(count).filter(c -> c != 0).count() == 0;
  }

  private void dfs(Node root, int[] count, int add) {
    if (root == null)
      return;
    if ('a' <= root.val && root.val <= 'z')
      count[root.val - 'a'] += add;
    dfs(root.left, count, add);
    dfs(root.right, count, add);
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Solution:
  def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
    count = collections.Counter()

    def dfs(root: 'Node', add: int) -> None:
      if not root:
        return
      if 'a' <= root.val <= 'z':
        count[root.val] += add
      dfs(root.left, add)
      dfs(root.right, add)

    dfs(root1, 1)
    dfs(root2, -1)
    return all(value == 0 for value in count.values())