剑指offer树的子结构python

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

思路

首先遍历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
    

 

posted @ 2019-11-04 10:43  小小文艺范  阅读(172)  评论(0编辑  收藏  举报

contact me

email:78910421@qq.com