#100

Same Tree

Easy
TreeDepth-First SearchBreadth-First SearchBinary TreeTree TraversalRecursion
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(h)
💡

Intuition

Time O(n)Space O(h)

The optimal solution uses a recursive approach to check both trees simultaneously. This allows us to compare nodes in a single pass, improving efficiency.

⚙️

Algorithm

4 steps
  1. 1Step 1: If both nodes are null, return true.
  2. 2Step 2: If one node is null and the other is not, return false.
  3. 3Step 3: If the values of both nodes are different, return false.
  4. 4Step 4: Recursively check the left and right children of both nodes.
solution.py8 lines
1def isSameTree(p, q):
2    if not p and not q:
3        return True
4    if not p or not q:
5        return False
6    if p.val != q.val:
7        return False
8    return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)

Complexity note: The time complexity is O(n) because we visit each node once. The space complexity is O(h) due to the recursion stack, where h is the height of the tree.

  • 1Both trees must have the same structure and node values to be considered identical.
  • 2Recursive traversal is a natural fit for tree problems.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.