PracticeNeetCode ↗LeetCode ↗
Given the roots of two binary trees root and subRoot, return true if there exists a subtree of root with exactly the same structure and node values as subRoot.
Time: O(n · m) worst case — Space: O(h)
def isSubtree(root: TreeNode | None, subRoot: TreeNode | None) -> bool:
if not root:
return False
if isSameTree(root, subRoot):
return True
return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
def isSameTree(p: TreeNode | None, q: TreeNode | None) -> bool:
if not p and not q:
return True
if not p or not q:
return False
if p.val != q.val:
return False
return isSameTree(p.left, q.left) and isSameTree(p.right, q.right)How the solution above works, piece by piece.
root means no match was found on this path → False.subRoot (using isSameTree), done.isSameTree is the node-by-node comparison from the Same Tree problem.Running it on root = [3, 4, 5, 1, 2], subRoot = [4, 1, 2]:
root is a possible starting point. At 3 the values differ; at 4 the whole subtree (4, 1, 2) matches subRoot exactly, so the answer is True.