AceYourInterviews
Checking sign-in…

79. Same Tree

CoreMatch ordered child positions, nullness, and values

Check whether the trees have a node in exactly the same positions and whether corresponding nodes hold equal values. Both shape and values matter.

Matching traversals or matching sets of values alone are insufficient. Missing children must occur on the same sides.

Example 1

Input

a=[1,2,3], b=[1,2,3]

Output

true

Explanation: Independent allocations can be equal trees.

Example 2

Input

a=[1,2], b=[1,null,2]

Output

false

Explanation: The values occur on different child sides; traversal values without null positions are insufficient.

Constraints

  • 0 <= node count per tree <= 105
  • -231 <= node.value <= 231 - 1
  • Each input is a proper binary tree: no cycles or shared child nodes. Null trees are permitted.
Hints
Hint 1

A node value alone does not describe its position.

Hint 2

A comparison item should contain one reference from each input.

Hint 3

Reject null/value mismatches; otherwise queue matching left/left and right/right pairs.

Practice on LeetCode ↗
Code
Saved on this deviceLn 1, Col 1

Independent equal trees with duplicates

[1,2,2]
[1,2,2]
true