【剑指Offer】18树的子结构
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
时间限制:1秒;空间限制:32768K
解题思路
解题思路分为两步,主要用到了递归的方法。第一步先遍历树A,找到和树B根节点值相同的节点A';第二步判断以A'为根节点的子树中是否包含树B。
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
# write code here
result = False
if pRoot1!=None and pRoot2!=None:
if pRoot1.val == pRoot2.val:
result = self.iscomprise(pRoot1,pRoot2) #不写self.会报错
if result != True:
result = self.HasSubtree(pRoot1.left,pRoot2)
if result != True:
result = self.HasSubtree(pRoot1.right,pRoot2)
return result
def iscomprise(self, pRoot1, pRoot2):
if pRoot2 == None:
return True
if pRoot1 == None:
return False
if pRoot1.val == pRoot2.val:
return self.iscomprise(pRoot1.left, pRoot2.left) and self.iscomprise(pRoot1.right, pRoot2.right)