标签:desc describe root __init__ offer 遍历 content item 二叉树
首先遍历a树,找和b树根结点值相等的结点,找到后判断是不是子树。
判断是不是子树的时候,用递归的方法,判断根节点,再判断左子右子。
# -*- 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 result = False if pRoot1 and pRoot2: if pRoot1.val == pRoot2.val: result = self.isSubtree(pRoot1,pRoot2) if not result and pRoot1.left: result = self.isSubtree(pRoot1.left,pRoot2) if not result and pRoot2.right: result = self.isSubtree(pRoot1.right,pRoot2) return result def isSubtree(self,p1,p2): if not p2: return True if not p1: return False if p1.val != p2.val: return False check_left = self.isSubtree(p1.left, p2.left) check_right = self.isSubtree(p1.right,p2.right) return check_left and check_right
标签:desc describe root __init__ offer 遍历 content item 二叉树
原文地址:https://www.cnblogs.com/wangzhihang/p/11790889.html