题目描述:
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:
递归
class Tree:
def __init__(self,x):
self.val = x
self.left = None
self.right = None
def is_subtree(self,A,B):
if not B:
retutn False
if not A or A.val != B.val:
return False
return self.is_subtree(A.left,B.left) and self.is_subtree(A.right,B.right)
def hassubtree(self,proot1,proot2):
if not proot1 or proot2:
return False
return self.is_subtree(proot1,proot2) or self.hassubtree(proot1.left,proot2) or self.hassubtree(proot1.right,proot2)