Problem 418792 · easy · Phase 04 Non-Linear Data Structures

Identical Trees

binary trees · recursion · structural comparison

Given the roots p and q of two binary trees, return True if the trees are identical: same shape and the same value at every corresponding position. Two empty trees are identical.

Examples

    1        1
   / \      / \
  2   3    2   3

Input:  p = build_tree([1, 2, 3]), q = build_tree([1, 2, 3])
Output: True
    1        1
   /          \
  2            2

Input:  p = build_tree([1, 2]), q = build_tree([1, None, 2])
Output: False
Explanation: same values, but 2 hangs on different sides.

Constraints

  • 0 <= number of nodes in each tree <= 2000
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n) time.

Goals

  • Compare two trees node by node
  • Treat a None/non-None mismatch as a structural difference
  • Recurse on matching child pairs
Starting Python…