给两棵非空的二分树s、t,判断t是否是s的一个子集。子集指的是:从s的某个结点开始,其下的结构与t完全相同。
Ex1:
s: t:
3 4
/ \ / \
4 5 1 2
/ \
1 2 Output:True
Ex2:
s: t:
3 4
/ \ / \
4 5 1 2
/ \
1 2
/
0 Output:False
class Solution:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def sameTree(s, t):
if not s and not t:return True
if not s or not t:return False
return s.val == t.val and sameTree(s.left, t.left) and sameTree(s.right, t.right)
if sameTree(s, t):return True
if not s:return False
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)