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

Twin Bonsai Check

binary trees · recursion · structural comparison

A nursery shapes its bonsai to a pattern and wants to check two of them against each other. Each one is a binary tree, with roots p and q. Return True if they are exact copies (identical): the same branching shape and the same value at every matching position. Two empty trees are copies.

Examples

    5        5
   / \      / \
  8   2    8   2

Input:  p = build_tree([5, 8, 2]), q = build_tree([5, 8, 2])
Output: True
    6        6
   /          \
  4            4

Input:  p = build_tree([6, 4]), q = build_tree([6, None, 4])
Output: False
Explanation: same values, but 4 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…