Loading content...
You are given the roots of two binary trees: a primary tree called root and a candidate tree called candidate. Your task is to determine whether the candidate tree appears as an embedded subtree anywhere within the primary tree.
A tree T is considered an embedded subtree of another tree S if there exists a node in S such that the tree rooted at that node is structurally identical to T and contains exactly the same node values in the same positions. In other words, starting from some node in S, the entire structure below it must match the candidate tree exactly—including the shape, values, and the presence or absence of children.
Note that the primary tree itself qualifies as its own embedded subtree (when the matching node is the root).
Return true if such an embedded subtree exists within the primary tree, and false otherwise.
root = [3,4,5,1,2]
candidate = [4,1,2]trueThe subtree rooted at the node with value 4 in the primary tree has the exact same structure and values as the candidate tree [4,1,2]. Both have node 4 as root with left child 1 and right child 2.
root = [3,4,5,1,2,null,null,null,null,0]
candidate = [4,1,2]falseAlthough the primary tree contains a node with value 4 that has children 1 and 2, the node with value 2 in the primary tree has an additional left child with value 0. This extra node makes the structures different, so the candidate is not an embedded subtree.
root = [1,2,3]
candidate = [2]trueThe node with value 2 in the primary tree has no children, which exactly matches the candidate tree containing only a single node with value 2. The structures are identical.
Constraints