zoukankan      html  css  js  c++  java
  • 17.树的子结构(python)

    题目描述

    输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
     1 class Solution:
     2     def HasSubtree(self, pRoot1, pRoot2):
     3         # write code here
     4         if pRoot1==None or pRoot2==None:
     5             return False
     6         def getEqual(pRoot1,pRoot2):
     7             if pRoot2==None:
     8                 return True
     9             if pRoot1==None:
    10                 return False
    11             if pRoot1.val == pRoot2.val:
    12                 if pRoot2.left==None:
    13                     leftEqual=True
    14                 else:
    15                     leftEqual=getEqual(pRoot1.left,pRoot2.left)
    16                 if pRoot2.right==None:
    17                     rightEqual=True
    18                 else:
    19                     rightEqual=getEqual(pRoot1.right,pRoot2.right)
    20                 return leftEqual and rightEqual
    21             return False
    22         
    23         if pRoot1.val == pRoot2.val:
    24             ret = getEqual(pRoot1,pRoot2)
    25             if ret:
    26                 return True
    27         ret = self.HasSubtree(pRoot1.left,pRoot2)
    28         if ret:
    29             return True
    30         ret = self.HasSubtree(pRoot1.right,pRoot2)
    31         return ret

    2019-12-09 18:40:20

  • 相关阅读:
    牛客练习赛24 E:青蛙(最短路)
    菜根谭#10
    菜根谭#9
    菜根谭#8
    菜根谭#7
    菜根谭#6
    菜根谭#5
    菜根谭#4
    菜根谭#3
    菜根谭#2
  • 原文地址:https://www.cnblogs.com/NPC-assange/p/12012781.html
Copyright © 2011-2022 走看看