CodeArchon

easyTreesGoogleAmazonFacebook

Subassembly Matcher

An industrial factory scanner analyzes modular blue-prints to determine if a smaller sub-assembly configuration exists exactly inside a larger system layout.

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 of `subRoot`.

Choose approach

⚙
3
4
5
1
2
4
1
2
1/6
Narrationstep 1 of 6

Scan Main blueprint (Left) to locate sub-assembly template (Right).

1def isSubtree(root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
2 if not root:
3 return False
4 if isSame(root, subRoot):
5 return True
6 return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
7
8def isSame(p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
9 if not p and not q:
10 return True
11 if not p or not q:
12 return False
13 return p.val == q.val and isSame(p.left, q.left) and isSame(p.right, q.right)
Variables
status=Scan start

How to think about it

  1. Traverse main tree to find matching root values.
  2. When target candidates match, compare shapes node by node.
  3. If identity check matches completely, bubble up True.

Edge cases to catch in interview

  • Sub-root empty -> always vacuously true.
  • Blueprint empty but sub-root exists -> false.

Examples

Example 1true
{"mainArr":[3,4,5,1,2],"subArr":[4,1,2]}
Example 2false
{"mainArr":[3,4,5,1,2,null,null,null,null,0],"subArr":[4,1,2]}

Try your own input

SpacePlay / pause
← / →Previous / next step
RReset to start
. or >Cycle speed