题目描述:Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants. The tree s could also be considered as a subtree of itself.
示例:
Example 1:
Given tree s:
3 / \ 4 5 / \ 1 2Given tree t:
4 / \ 1 2Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3 / \ 4 5 / \ 1 2 / 0Given tree t:
4 / \ 1 2
Return false.
思想:树的题目都是递归来的多,首先应该判断相同部分是否从根节点开始,若不是递归判断左右子树。
class Solution:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if s is None or t is None:
return s is None and t is None
if self.isSame(s, t):
return True
else:
return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
def isSame(self, s, t):
if not s:
return not t
if not t:
return not s
left = self.isSame(s.left, t.left)
mid = (s.val == t.val)
right = self.isSame(s.right, t.right)
return left and mid and right
展示一位大神的代码,把树打印成字符串,再比较字符串t是否在s中,这种做法期初会有个漏洞,就是第二种例子的情况,本做法用l,r分别标识就巧妙地避免了这种尴尬。太赞了
class Solution:
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
def treeToString(root, s = ""):
if root:
return treeToString(root.left,"l") + str(root.val) + treeToString(root.right, "r")
return s
stringS = treeToString(s)
stringT = treeToString(t)
if stringT not in stringS:
return False
return True