subtree-of-another-tree.sh — zsh
binary-treedepth-first-searchrecursion

Given the roots of two binary trees root and subRoot, return true if there is a subtree of root with the same structure and node values as subRoot, and false otherwise.

A subtree of a binary tree tree is a tree that consists of a node in tree and all of that node's descendants. The tree tree can also be considered a subtree of itself.

Input / output

  • Input: root: TreeNode, subRoot: TreeNode (represented in level-order array form in test fixtures)
  • Output: boolean

Constraints

  • The number of nodes in root is in the range [1, 2000]
  • The number of nodes in subRoot is in the range [1, 1000]
  • -10^4 <= root.val, subRoot.val <= 10^4

Follow-up

Can you solve this in O(m + n) time by serializing both trees with explicit null markers and running KMP or rolling-hash substring search?

Examples
Example 1
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: true
Example 2: extra descendant breaks match
Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
Output: false
Example 3: duplicate value at root and leaf
Input: root = [1,1], subRoot = [1]
Output: true