Blind 75
27 / 75Free practice

Same Tree

Easy · Trees

Jump to code

Determine whether two binary trees have identical structure and matching values at every corresponding node.

Examples

Example 1

p = [1,2,3]
q = [1,2,3]

Output: true

Example 2

p = [1,2]
q = [1,null,2]

Output: false

Constraints

  • 0 <= The number of nodes in both trees <= 100
  • -100 <= Node.val <= 100

Function contract

Trees use level-order arrays, with null for a missing child. Your code receives TreeNode objects with val, left, and right fields.

Need a hint?

Null positions are part of the structure.

Real tree interview questions

Questions on the same topic that candidates reported from real company interviews. Some company questions are locked and open with Premium or XP.

Browse all real coding interview questions

Accepted submissions mark this problem complete. Progress stays in this browser.

Run checks 5 examples. Submit checks all 7 cases. A free account runs this problem; no XP needed.
Language
Case 1
Input
[
  [
    1,
    2,
    3
  ],
  [
    1,
    2,
    3
  ]
]
Expected
true
Case 2
Input
[
  [
    1,
    2
  ],
  [
    1,
    null,
    2
  ]
]
Expected
false
Case 3
Input
[
  [
    1,
    2,
    1
  ],
  [
    1,
    1,
    2
  ]
]
Expected
false
Case 4
Input
[
  [],
  []
]
Expected
true
Case 5
Input
[
  [
    1
  ],
  []
]
Expected
false

Drafts are saved per language in this browser when storage is available.