Subtree of Another Tree

EasyTrees and recursionAlso known as LeetCode 572

You get the roots of two binary trees, root and subRoot. Return true if there is a node in root whose whole subtree (that node and all of its descendants) is identical to subRoot in shape and in values. Otherwise return false.

The tree root counts as a subtree of itself. Both trees are written in level order, with null for a missing child.

Examples

root
root: a binary tree with 5 nodes and 3 levels, root 3.34512
subRoot
subRoot: a binary tree with 3 nodes and 2 levels, root 4.412
Input root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]
Output true
root
root: a binary tree with 6 nodes and 4 levels, root 3.345120
subRoot
subRoot: a binary tree with 3 nodes and 2 levels, root 4.412
Input root = [3, 4, 5, 1, 2, null, null, null, null, 0], subRoot = [4, 1, 2]
Output false
The node 2 has an extra child 0 in root.
root
root: a binary tree with 2 nodes and 2 levels, root 1.11
subRoot
subRoot: a binary tree with 1 node and 1 level, root 1.1
Input root = [1, 1], subRoot = [1]
Output true
The leaf 1 is a subtree.

Constraints

  • 1 <= number of nodes in root <= 200
  • 1 <= number of nodes in subRoot <= 100
  • -10,000 <= node value <= 10,000

Stuck? Take one hint at a time

Common mistakes
  • Checking only the root values and ignoring the rest of the subtree, which accepts a node with extra descendants.
  • Leaving out the marker for empty children in the string version, so different shapes give the same string.
  • Leaving out the separator before each value, so 12 matches inside 112.
  • Calling the same-tree check only at the root of the big tree, instead of at every node.
Questions an interviewer may ask next
  • Count how many times subRoot appears in root.
  • Return the node where the subtree starts. (The same walk, returning the node.)
  • Make the string version fast in the worst case. (Use a linear time search such as KMP, or hash the subtrees.)
  • Allow the shape to match but not the values (an unlabeled subtree). Which approach still works?