572. Subtree of Another Tree
[Easy] “Given two non-empty binary trees s and t, check whether tree t is a subtree of tree s."
Python3:
# 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
class Solution:
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if s:
return self.isMatch(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
else:
return False
def isMatch(self, s, t):
if (s and not t) or (t and not s):
return False
elif not t and not s:
return True
if s.val == t.val:
if self.isMatch(s.left, t.left) and self.isMatch(s.right, t.right):
return True
else:
return False