题目描述
- 输入两棵二叉树A,B
- 判断B是不是A的子结构。
- 其中空树不是任意一个树的子结构
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
解题思路
思路1
class Solution:
def HasSubtree(self, pRoot1, pRoot2):
if pRoot1 == None or pRoot2 == None:
return False
return self.is_Subtree(pRoot1,pRoot2) or self.HasSubtree(pRoot1.left,pRoot2) or self.HasSubtree(pRoot1.right,pRoot2)
def is_Subtree(self,pRoot1,pRoot2):
if pRoot2 == None:
return True
elif pRoot1 == None or pRoot1.val != pRoot2.val:
return False
return self.is_Subtree(pRoot1.left,pRoot2.left) and self.is_Subtree(pRoot1.right,pRoot2.right)