码迷,mamicode.com
首页 > 其他好文 > 详细

树的子结构(important!)

时间:2019-03-02 18:25:50      阅读:166      评论:0      收藏:0      [点我收藏+]

标签: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)

树的子结构(important!)

标签:python   sel   ini   als   and   树的子结构   题目   nod   ant   

原文地址:https://www.cnblogs.com/bernieloveslife/p/10423902.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!