算法题:树的子结构
作者:互联网
题目:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
思路:遍历二叉树A,将每个结点与二叉树B的根节点比较,若相等,则从A的该节点开始递归比较是否完全包含B的结构,如果是则输出True,否则遍历A的下一个结点,直到A全部遍历输出False
# -*- 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): if pRoot1 == None or pRoot2 == None: return False return self.isSubtree(pRoot1,pRoot2) or self.isSubtree(pRoot1.left,pRoot2) or self.isSubtree(pRoot1.right,pRoot2) def isSubtree(self, pRoot1, pRoot2): if pRoot2 == None: return True if pRoot1 == None: return False return pRoot1.val == pRoot2.val and self.isSubtree(pRoot1.left,pRoot2.left) and self.isSubtree(pRoot1.right,pRoot2.right)
标签:None,return,self,isSubtree,pRoot2,子结构,pRoot1,算法 来源: https://www.cnblogs.com/yrzsp/p/10945978.html