题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
tips:先序遍历中,在遍历时添加两个节点处的判断。判断函数从节点处开始往左右子树递归。
# -*- 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
if pRoot1 and pRoot2:
return self.calibrate(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
else:
return False
def calibrate(self,a,b):
if not b:
return True
if not a:
return False
if a.val!=b.val:
return False
return self.calibrate(a.left,b.left) and self.calibrate(a.right,b.right)