Skip to main content

11. Same Tree

easyAsked at Expedia

Check if two binary trees are structurally identical with same node values.

By Alex Chen, Founder, InterviewChamp.AI · Last verified

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.

Constraints

  • Number of nodes in both trees is in [0, 100]
  • -10^4 <= Node.val <= 10^4

Examples

Example 1

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

Example 2

Input
p = [1,2], q = [1,null,2]
Output
false

Approaches

1. Serialize and compare

Serialize both trees and compare strings.

Time
O(n)
Space
O(n)
function ser(n){if(!n) return '#';return n.val+','+ser(n.left)+','+ser(n.right);}
return ser(p)===ser(q);

Tradeoff:

2. Recursive structural equality

Compare current values, recurse left and right. Expedia uses this for cache-invalidation diff of itinerary trees.

Time
O(n)
Space
O(h)
function isSameTree(p, q) {
  if (!p && !q) return true;
  if (!p || !q) return false;
  if (p.val !== q.val) return false;
  return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}

Tradeoff:

Expedia-specific tips

Expedia interviewers often ask 'what changes if values are floats?' — your answer should call out epsilon-comparison since pricing data is floating-point.

Solve it now

Free. No sign-up. Python and JavaScript run instantly in your browser.

Output

Press Run or Cmd+Enter to execute

Practice these live with InterviewChamp.AI

Drill Same Tree and other Expedia interview questions under real-loop conditions with instant feedback on your reasoning, complexity claims, and code.

Practice these live with InterviewChamp.AI →