原題是:
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.
Screen Shot 2017-11-09 at 9.18.11 AM.png
思路是:
之前刷過一道題武氓,叫做sameTree梯皿,就是比較兩個樹是否完全相同搪柑。這個可以應(yīng)用到本題中來,只需逐個比較s中的每個節(jié)點(diǎn)為Root的樹和t是否互為相同樹索烹。
代碼是:
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSubtree(self, s, t):
"""
:type s: TreeNode
:type t: TreeNode
:rtype: bool
"""
if s == None:
return False
elif self.sameTree(s,t):
return True
elif self.isSubtree(s.left,t):
return True
elif self.isSubtree(s.right,t):
return True
return False
def sameTree(self,root1,root2):
if not (root1 or root2):
return True
elif not(root1 and root2):
return False
elif root1.val == root2.val:
Left = self.sameTree(root1.left,root2.left)
Right = self.sameTree(root1.right,root2.right)
if Left and Right:
return True
return False