Skip to main content

1612. Check If Two Expression Trees are Equivalent

Python

class Solution:
def checkEquivalence(self, root1: 'Node', root2: 'Node') -> bool:
root1_operand = sorted(self.extract_operand(root1, []))
root2_operand = sorted(self.extract_operand(root2, []))

if len(root1_operand) != len(root2_operand):
return False

for i in range(len(root1_operand)):
if root1_operand[i] != root2_operand[i]:
return False
return True


def extract_operand(self, node, holder: list):
if not node:
return

if node.val != '+':
holder.append(node.val)
self.extract_operand(node.left, holder)
self.extract_operand(node.right, holder)

return holder