LeetCode 1612. Check If Two Expression Trees are Equivalent Solution in Java, C++, Python & JavaScript | Explanation + Code

CoderIndeed
0
1612. Check If Two Expression Trees are Equivalent

Description

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.

 

Example 1:

Input: root1 = [x], root2 = [x]
Output: true

Example 2:

Input: root1 = [+,a,+,null,null,b,c], root2 = [+,+,a,b,c]
Output: true
Explanation: a + (b + c) == (b + c) + a

Example 3:

Input: root1 = [+,a,+,null,null,b,c], root2 = [+,+,a,b,d]
Output: false
Explanation: a + (b + c) != (b + d) + a

 

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.

 

Follow up: What will you change in your solution if the tree also supports the '-' operator (i.e. subtraction)?

Solutions

Solution 1

PythonJavaC++JavaScript
# Definition for a binary tree node. # class Node(object): # def __init__(self, val=" ", left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: def dfs(root, v): if root is None: return if root.val != '+': cnt[root.val] += v dfs(root.left, v) dfs(root.right, v) cnt = Counter() dfs(root1, 1) dfs(root2, -1) return all(x == 0 for x in cnt.values())(code-box)

Solution 2

PythonJavaC++JavaScript
# Definition for a binary tree node. # class Node(object): # def __init__(self, val=" ", left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool: def dfs(root): cnt = [0] * 26 if root is None: return cnt if root.val in '+-': l, r = dfs(root.left), dfs(root.right) k = 1 if root.val == '+' else -1 for i in range(26): cnt[i] += l[i] + r[i] * k else: cnt[ord(root.val) - ord('a')] += 1 return cnt return dfs(root1) == dfs(root2)(code-box)

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !