EASY NC#50 Blind #61 Trees

100. Same Tree

๐Ÿ“– 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.

๐Ÿง  Visual Learning Aid

1 Model the input into the right structure
2 Choose the core technique and invariant
3 Execute step-by-step with a sample
4 Validate complexity and edge cases

JS/TS Refreshers

  • โ€ขArray methods (`push`, `pop`, `shift`, `slice`)
  • โ€ขObject/Map/Set usage patterns
  • โ€ขFunction parameter and return typing
  • โ€ขLevel-order traversal
  • โ€ขQueue discipline
  • โ€ขShortest-step interpretation

Logical Thinking Concepts

  • โ€ขDefine invariants before coding
  • โ€ขCheck edge cases first (`[]`, single element, duplicates)
  • โ€ขEstimate time/space before implementation
  • โ€ขApply BFS reasoning pattern
  • โ€ขApply Recursion reasoning pattern

๐Ÿ’ก Approach

  • โ†’ Use recursive approach to compare corresponding nodes
  • โ†’ Base case: both null (same), one null (different)
  • โ†’ Compare values and recursively check both subtrees
  • โ†’ Time: O(min(m, n)), Space: O(h) where h is tree height

๐Ÿ› ๏ธ Hints & Pitfalls

Hints

  • โ€ขUse recursive approach to compare corresponding nodes
  • โ€ขBase case: both null (same), one null (different)
  • โ€ขCompare values and recursively check both subtrees

Common Pitfalls

  • โ€ขTime: O(min(m, n)), Space: O(h) where h is tree height

๐Ÿงช Test Cases

Hidden tests on submit: 3

Test Case 1
Not run
Input:
buildTree([1,2,3]);
Expected:
{"val":1,"left":{"val":2,"left":null,"right":null},"right":{"val":3,"left":null,"right":null}}
Test Case 2
Not run
Input:
buildTree([1,2]);
Expected:
{"val":1,"left":{"val":2,"left":null,"right":null},"right":null}
Test Case 3
Not run
Input:
buildTree([1,null,2]);
Expected:
{"val":1,"left":null,"right":{"val":2,"left":null,"right":null}}

๐Ÿ“ Code Editor

๐Ÿ“š Reference Solution

โ–ผ
โŒ˜K Search โŒ˜โ†ฉ Run โŒ˜S Submit