Same Tree — LeetCode 100 Python Solution
- Problem
- #100
- Pattern
- Tree Traversal
- Reading time
- 2 min
- Source
- leetcode.com
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
# 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
| Measure | Complexity |
|---|---|
| Time | O(\min(m, n)) |
| Space | O(\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.