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 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.
Input: root = [3,4,5,1,2], subRoot = [4,1,2]
Output: True
Input: root = [3,4,5,1,2,None,None,0], subRoot = [4,1,2]
Output: False
root
or subRoot
be None?from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def isSubtree(root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
if not subRoot:
return True # An empty tree is a subtree of any tree
if not root:
return False # Non-empty tree cannot be a subtree of an empty tree
if isSameTree(root, subRoot):
return True
return isSubtree(root.left, subRoot) or isSubtree(root.right, subRoot)
def isSameTree(s: Optional[TreeNode], t: Optional[TreeNode]) -> bool:
if not s and not t:
return True
if not s or not t:
return False
if s.val != t.val:
return False
return isSameTree(s.left, t.left) and isSameTree(s.right, t.right)
subRoot
is None
, then it is a subtree of any tree, thus return True
.root
is None
and subRoot
is not None
, then subRoot
cannot be a subtree of root
, thus return False
.isSameTree
to check if two trees are identical.isSameTree(root, subRoot)
returns True
, then subRoot
is indeed a subtree of root
.isSubtree
to check root.left
and root.right
.isSameTree
:
None
which means they are identical.None
and the other is not, return False
.False
.isSameTree
is O(n) where n
is the number of nodes in the trees being compared.root
is checked, and for each node, isSameTree
compares potentially m
nodes of subRoot
.N
is the number of nodes in root
and M
is the number of nodes in subRoot
.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?