Check If Two Expression Trees are Equivalent — LeetCode 1612 Python Solution

MediumLeetCode PremiumTreeDepth-First SearchHash TableBinary TreeCounting
Problem
#1612
Reading time
4 min

The problem

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.

Example

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

Python solution

Python
# 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())

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1612. Check If Two Expression Trees are Equivalent is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1612. Check If Two Expression Trees are Equivalent?
LeetCode 1612. Check If Two Expression Trees are Equivalent is rated Medium on LeetCode.
What is the time complexity of LeetCode 1612. Check If Two Expression Trees are Equivalent?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1612. Check If Two Expression Trees are Equivalent?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1612. Check If Two Expression Trees are Equivalent cover?
LeetCode 1612. Check If Two Expression Trees are Equivalent is tagged Tree, Depth-First Search, Hash Table, Binary Tree and Counting on LeetCode.
Is LeetCode 1612. Check If Two Expression Trees are Equivalent a premium problem?
Yes. LeetCode 1612. Check If Two Expression Trees are Equivalent is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview