Example 1
- Input
- root = [3,4,5,1,2], subRoot = [4,1,2]
- Output
- true
The node with value 4 in root has children 1 and 2, exactly matching subRoot.
Given two binary trees called root and subRoot, decide whether root contains a subtree with exactly the same structure and node values as subRoot. A subtree is a node together with all of its descendants, and the whole tree counts as a subtree of itself.
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 this node's descendants. The tree tree itself is also considered a subtree of tree, so identical trees are a match.
root contains between 1 and 2000 nodes.subRoot contains between 1 and 1000 nodes.null for a missing child.The node with value 4 in root has children 1 and 2, exactly matching subRoot.
The entire single-node tree is a valid subtree. Its value and both absent child slots match.
The candidate node 4 looks right, but its child 2 has an extra child 0, so the structures differ.
The first 1 fails because its left child is 1, not 2. The second 1 has exactly the left child 2, so searching must continue after a failed candidate.
Separate finding a candidate root from proving an exact match. In Example 1, 3 cannot match target root 4, but its left child 4 can: every descendant and missing child agrees. A candidate with an extra descendant fails because a subtree includes all descendants; you cannot prune it to fit the target.
Reveal Check Every Node: intuition, complexity, and code
2 must not match within 12, and negative values must remain distinct whole tokens.[1,2] and [1,null,2] then have the same value visits.A structural search can be reduced to sequence matching when the encoding is unambiguous and each candidate occupies a contiguous block. Keep missing-child markers, compare whole tokens, and use a proven linear matcher to remove repeated work.