树的子结构 牛客网 剑指Offer

树的子结构 牛客网 剑指Offer

  • 题目描述
  • 输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
class Solution:
    #run:27ms memory:5612k
    def HasSubtree(self, pRoot1, pRoot2):
        ret = False
        if pRoot2 is None or pRoot1 is None:
            return ret 
        if pRoot1.val == pRoot2.val:
            ret  = self.doesTree1HasTree2(pRoot1,pRoot2)
        if ret == False:
            ret = self.HasSubtree(pRoot1.left,pRoot2)
        if ret == False:
            ret = self.HasSubtree(pRoot1.right,pRoot2)
        return  ret 
    
    def doesTree1HasTree2(self,pRoot1,pRoot2):
        if pRoot2 == None:
            return True
        if pRoot1 == None:
            return False
        if pRoot1.val != pRoot2.val:
            return False
        return self.doesTree1HasTree2(pRoot1.left,pRoot2.left) and self.doesTree1HasTree2(pRoot1.right,pRoot2.right)

 

posted @ 2018-09-12 16:00  vercont  阅读(104)  评论(0编辑  收藏  举报