标签:python sel ini als and 树的子结构 题目 nod ant
题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
python solution:
# -*- 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 is None or pRoot2 is None:
return False
res = False
if pRoot1.val==pRoot2.val:
res = self.doeshtree1havetree2(pRoot1,pRoot2)
if res is False:
res = self.HasSubtree(pRoot1.left,pRoot2)
if res is False:
res = self.HasSubtree(pRoot1.right,pRoot2)
return res
def doeshtree1havetree2(self,proot1,proot2): #判断以proot1和proot2为根节点的两个树是否相同
if proot2 is None:
return True
if proot1 is None:
return False
if proot1.val!=proot2.val:
return False
return self.doeshtree1havetree2(proot1.left,proot2.left) and self.doeshtree1havetree2(proot1.right,proot2.right)
标签:python sel ini als and 树的子结构 题目 nod ant
原文地址:https://www.cnblogs.com/bernieloveslife/p/10423902.html