#572
Subtree of Another Tree
easy· Treesruns: 0Given 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.
sign in to paste and practice your own solution
wpm 0acc 100%time 0:000 / 702
class Solution:
def isSubtree(
self, root: TreeNode | None, subRoot: TreeNode | None
) -> bool:
if not subRoot:
return True
if not root:
return False
if self.isSameTree(root, subRoot):
return True
return self.isSubtree(root.left, subRoot) or self.isSubtree(
root.right, subRoot
)
def isSameTree(
self, p: TreeNode | None, q: TreeNode | None
) -> bool:
if not p and not q:
return True
if not p or not q or p.val != q.val:
return False
return self.isSameTree(p.left, q.left) and self.isSameTree(
p.right, q.right
)
click the box to focus · tab inserts 4 spaces · backspace to correct · esc to pause
desktop only
codedrill is a typing game and needs a real keyboard. open this on a laptop or desktop to practice.
you can still browse problems and sections from your phone.