Problem 494748 · medium · Level 04 Non-Linear Data Structures

Contains Subtree

binary trees · recursion · structural comparison

Given the roots of two binary trees root and sub, return True if some node of root, together with all of its descendants, forms a tree identical to sub. An empty sub is always contained.

Examples

   6            9
  / \          / \
 2   9        5   7
    / \
   5   7

Input:  root = build_tree([6, 2, 9, None, None, 5, 7]), sub = build_tree([9, 5, 7])
Output: True
   6            9
  / \          / \
 2   9        5   7
    / \
   5   7
  /
 1

Input:  root = build_tree([6, 2, 9, None, None, 5, 7, None, None, 1]), sub = build_tree([9, 5, 7])
Output: False
Explanation: the node 9 has an extra descendant 1, so its subtree is not identical to sub.

Constraints

  • 0 <= number of nodes in root <= 2000, 0 <= number of nodes in sub <= 100
  • -10**4 <= node.val <= 10**4
  • Target complexity: O(n * m) time is acceptable.

Goals

  • Reuse an 'identical trees' helper at every candidate node
  • Understand that a subtree includes all descendants of its root
  • Handle the empty subtree
Starting Python…