【Leetcode】572. Subtree of Another Tree 解题报告
作者:互联网
求一棵树是不是另一棵树的子树
方法1 双递归
对母树的每个节点进行访问,判断以该节点为定点的树是不是和子树相同
class Solution1:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if s == None:
return False
if self.isSame(s, t):
return True
else:
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSame(self, rootA, rootB):
if rootA == None and rootB == None:
return True
if rootA == None or rootB == None:
return False
else:
if rootA.val != rootB.val:
return False
else:
return self.isSame(rootA.left, rootB.left) and self.isSame(rootA.right, rootB.right)
方法2 方法1的非递归形式
class Solution2:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if s == None:
return False
stack = [s]
while(len(stack)):
node = stack.pop()
if self.isSame(node, t):
return True
else:
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return False
def isSame(self, rootA, rootB):
stack = [[rootA, rootB]]
while(len(stack)):
nodeA,nodeB = stack.pop()
if nodeA == None and nodeB == None:
continue
else:
if nodeA == None or nodeB == None:
if nodeA != nodeB:
return False
else:
if nodeA.val != nodeB.val:
return False
else:
stack.append([nodeA.left, nodeB.left])
stack.append([nodeA.right, nodeB.right])
return True
方法3 序列化法
求出母树和子树的字符串,看子树的字符串和是否在母树的字符串。
注:遍历二叉树的时候必须用先序遍历,而且每个节点要访问完其左右子节点为止(就算为None也要访问)
class Solution3:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
s_string = []
t_string = []
self.serialize(s, s_string)
self.serialize(t, t_string)
return "".join(t_string) in "".join(t_string)
def serialize(self, root, path):
if root == None:
path.append(",#")
else:
path.append(",%s"%(str(root.val)))
self.serialize(root.left, path)
self.serialize(root.right, path)
标签:None,right,return,572,self,Tree,Subtree,rootB,stack 来源: https://blog.csdn.net/dpengwang/article/details/88086272