python剑指offer 实现树的子结构

2021-06-23 05:04

阅读:562

标签:实现   highlight   utf-8   roo   val   one   pytho   输入   tom   

题目描述

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
# -*- 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
        if not pRoot1 or not pRoot2:
            return False
        if pRoot1.val == pRoot2.val:
            return self.DoesTree1HaveTrees(pRoot1,pRoot2)
        return self.HasSubtree(pRoot1.left, pRoot2) or self.HasSubtree(pRoot1.right, pRoot2)

    def DoesTree1HaveTrees(self,pRoot1,pRoot2):
        if not pRoot2:
            return True
        if not pRoot1 or pRoot1.val == pRoot1.val:
            return False
        return self.DoesTree1HaveTrees(pRoot1.left,pRoot2.left) and self.DoesTree1HaveTrees(pRoot1.right,pRoot2.right)

 

python剑指offer 实现树的子结构

标签:实现   highlight   utf-8   roo   val   one   pytho   输入   tom   

原文地址:https://www.cnblogs.com/tianqizhi/p/9674680.html


评论


亲,登录后才可以留言!