CodeArchon

easyTreesAmazonGoogleMicrosoft

Structural Sync Auditor

An administrator compares a backup folder hierarchy against a source schema to confirm structures match completely in metadata and order.

Given the roots of two binary trees `p` and `q`, write a function to check if they are structurally identical, and nodes have same values.

Choose approach

Verification Root
1
2
3
1
2
3
1/12
Narrationstep 1 of 12

Compare directories side-by-side (Left: Sync P, Right: Sync Q).

1def isSameTree(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
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)
Variables
comparing=Verify match

How to think about it

  1. If both nodes are null -> true.
  2. If only one node is null -> false.
  3. If structural values differ -> false.
  4. Recursively compare left subtrees AND right subtrees.

Edge cases to catch in interview

  • Both trees empty -> true.
  • Vastly different sizes -> fail fast on first size discrepancy.

Examples

Example 1true
{"aArr":[1,2,3],"bArr":[1,2,3]}
Example 2false
{"aArr":[1,2],"bArr":[1,null,2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed