Coders Crushby Napplied AI
Back to DSA Problems
EasyTrees

Same Tree

Check if two trees are same

Solution Approach

Recursively compare node values and subtrees. Both must be null or have same value and structure.

Implementation
def isSameTree(p, q):
    if not p and not q:
        return True
    if not p or not q:
        return False
    return (p.val == q.val and 
            isSameTree(p.left, q.left) and 
            isSameTree(p.right, q.right))
Complexity Analysis

Time Complexity

O(min(m,n))

Space Complexity

O(min(h1,h2))
Complexity
Time:O(min(m,n))
Space:O(min(h1,h2))
Asked at
GoogleAmazon
Coders Crushby Napplied AI

The ultimate interview preparation platform. Master System Design, DSA, and tackle community challenges to crush your FAANG interviews.

Looking for jobs? Visit Napplied AI Jobs Search Agent

System Design

  • All Problems
  • Easy
  • Hard

DSA

  • All Problems
  • Dynamic Programming
  • Graphs

More

  • Problems Arena
  • Growth Paths
  • My Crush

Coders Crush by Napplied AI - Tech Interview & Coding Should Be Effortless