572. Subtree of Another Tree
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.
Example :
Input: root = [3,4,5,1,2], subRoot = [4,1,2] Output: true
SOLUTION:
class Solution: def isSubtree(self, r: Optional[TreeNode], sr: Optional[TreeNode]) -> bool: if not sr: return True if not r: return False if self.sameTree(r,sr): return True return (self.isSubtree(r.left, sr) or self.isSubtree(r.right, sr)) def sameTree(self, r, sr): if not r and not sr: return True if r and sr and r.val == sr.val: return (self.sameTree(r.left, sr.left) and self.sameTree(r.right, sr.right)) return False
Explaination :
Comments
Post a Comment