Same Tree — LeetCode 100 Python Solution

EasyTreeDepth-First SearchBreadth-First SearchBinary Tree
Problem
#100
Reading time
2 min

The problem

Given the roots of two binary trees p and q, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical, and the nodes have the same value.

Example

Input
p = [1,2,3], q = [1,2,3]
Output
true

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p == q:
            return True
        if p is None or q is None or p.val != q.val:
            return False
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Complexity

MeasureComplexity
TimeO(\min(m, n))
SpaceO(\min(m, n)) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 100. Same Tree 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

On study lists

This problem is on Blind 75, NeetCode 150 and Top Interview 150.

Frequently asked questions

How hard is LeetCode 100. Same Tree?
LeetCode 100. Same Tree is rated Easy on LeetCode.
What is the time complexity of LeetCode 100. Same Tree?
The Python solution on this page runs in O(\min(m, n)).
What is the space complexity of LeetCode 100. Same Tree?
The Python solution on this page uses O(\min(m, n)) auxiliary space.
What topics does LeetCode 100. Same Tree cover?
LeetCode 100. Same Tree is tagged Tree, Depth-First Search, Breadth-First Search and Binary Tree on LeetCode.

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