1.DFS比较
2.将树转成字符串将问题转换成判断一个字符串是否是另一个字符串的字串
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def equaltree(self,s,t):
if not s and not t:
return True
if not s or not t:
return False
return s.val==t.val and self.equaltree(s.left,t.left) and self.equaltree(s.right,t.right)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if not s or not t:
return False
return self.equaltree(s,t) or self.isSubtree(s.left,t) or self.isSubtree(s.right,t)
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def treetostring(self,s):
if not s:
return '$'
return '*'+str(s.val)+self.treetostring(s.left)+self.treetostring(s.right)
def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
if not s and not t:
return True
if not s or not t:
return False
sstring=self.treetostring(s)
tstring=self.treetostring(t)
return tstring in sstring