Menu
CoddyTech

Subtree of Another Tree

You get two binary trees, root and subRoot, each stored in an array in level order: the root at index 0, the children of index i at 2*i+1 (left) and 2*i+2 (right), and -1 for an empty spot. An array may end with extra -1 entries.

Return true if some node of root, with all of its descendants, has exactly the shape and values of subRoot, and false otherwise. The whole of root counts too.

Function

isSubtree(root: integer-array, subRoot: integer-array) → boolean
rootinteger-array
the tree to search, in level order with -1 for an empty spot
subRootinteger-array
the tree to look for, in the same format
Returnsboolean
true if subRoot appears in root as a node with all its descendants, false otherwise

Constraints

  • 1 ≤ root.length ≤ 32767 and 1 ≤ subRoot.length ≤ 32767
  • Each entry is -1 or a value from 0 to 104.
  • root[0] and subRoot[0] are never -1, so both trees have at least one node.
  • Either array may end with extra -1 entries past its last node.
  • Both children of an empty spot are empty too, and each tree has a depth of at most 14.
  • Values may repeat.

Examples

Input
root = [6, 2, 8, 1, 3, -1, 9]subRoot = [2, 1, 3]
Output
true
Explanation
The node 2 at index 1 has the children 1 and 3, and both are leaves. That is exactly subRoot.
challenge icon

Follow-up

Can you fingerprint every subtree from its value and its children's fingerprints, so a comparison with subRoot costs O(1)? What do you do when two different subtrees collide?

Reset code
def isSubtree(root, subRoot):
    # Write code here

Test #1

Test #2

Test #3

Arguments

root = [6, 2, 8, 1, 3, -1, 9]
subRoot = [2, 1, 3]

Expected Output

true