A-051● Day 512026.06.26easyleetcode #572neetcode150
Subtree of Another Tree
#tree#depth-first-search#string-matching#binary-tree#hash-function
01
Problem
· problemGiven 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 and false otherwise. A subtree of a binary tree tree is a tree that consists of a node in tree and all of this node's descendants. The tree tree could also be considered as a subtree of itself.
constraints
- · 1 ≤ nodes in root ≤ 2000
- · 1 ≤ nodes in subRoot ≤ 1000
- · -10^4 ≤ node values ≤ 10^4
// paraphrased summary — see source for full text
examples
02
Pre-solve
· pre-solve● 1list shown→● 2select→● 3reveal
- ☐If subRoot is null, should we return true?
- ☐Does the subtree need to start at the root of the main tree?
- ☐If root = [4,1,2] and subRoot = [4,1,2], is subRoot a subtree of root?
- ☐Is [1,2] a subtree of [4,1,2] if both contain values 1 and 2?
- ☐Is it enough to check if root.val == subRoot.val for the root node?
- ☐Can we find subRoot by checking if its values appear in root in any order?
check the items you would ask, then press confirm
// session-only state — refresh resets (repeatable practice)
03
Logic Structure
· logic● 1slots shown→● 2pick per slot→● 3reveal
// pick one code line per slot to assemble the algorithm flow. no typing — just the logic skeleton.
step 1· Empty subRoot check
○
if not subRoot:
○
if subRoot: return True
○
if not subRoot: pass
step 2· Empty root check
○
if not root:
○
if not root: return True
○
if root and not subRoot: return False
step 3· Check if current subtree matches
○
if self.isSameTree(root, subRoot):
○
if root.val == subRoot.val:
○
if self.isSubtree(root, subRoot):
step 4· Recursively search left and right children
○
return self.isSubtree(root.left, subRoot) or self.isSubtree(root.right, subRoot)
○
return self.isSubtree(root.left, subRoot) and self.isSubtree(root.right, subRoot)
○
return self.isSubtree(root, subRoot.left) or self.isSubtree(root, subRoot.right)
pick one option per slot
// format: slot — recursive / DP patterns use ordering / state-first formats. ADR-08 follow-up.
04
Solve · Trace
· solvemental dry-run cases
// walk each case in your head; expand the worked example below if stuck.
case 1
[3,4,5,1,2] [4,1,2]→
true
case 2
[3,4,5,1,2,null,null,null,null,0] [4,1,2]→
false
// UI does not walk-through — you do the dry-run mentally. Expand the worked example if stuck.