题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:遍历树A中的节点,看与树B根节点的值是否相等,相等的话,递归比较左右子树。不相等的话,接着遍历树A。树的遍历也是使用递归的方式进行实现。需要注意的是,由于空树不是任意一个树的子结构,所以只有当两树都不为空时才进行判断B是否为A的子树。在比较相等节点的左右子树是否相等时,如果B已经为空了,那么说明已经找到了。如果B不为空但是A已经空了,那么说明没找到。
python题解:
# -*- 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 and pRoot2:
if pRoot1.val==pRoot2.val:
result=self.JudgeSubtree(pRoot1,pRoot2)
if not result:
result=self.HasSubtree(pRoot1.left,pRoot2)
if not result:
result=self.HasSubtree(pRoot1.right,pRoot2)
return result
def JudgeSubtree(self,pRoot1,pRoot2):
if not pRoot1 and pRoot2:
return False
if not pRoot2:
return True
if pRoot1.val!=pRoot2.val:
return False
return self.JudgeSubtree(pRoot1.left,pRoot2.left) and self.JudgeSubtree(pRoot1.right,pRoot2.right)