输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
# -*- 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 not pRoot1 or not pRoot2: return False return self.helper(pRoot1, pRoot2) or self.helper(pRoot1.left, pRoot2) or self.helper(pRoot1.right, pRoot2) def helper(self, p1, p2): if not p2: return True if not p1 and p2: return False if p1.val != p2.val: return False return self.helper(p1.left, p2.left) and self.helper(p1.right, p2.right)