首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Leetcode-Easy 572. Subtree of Another Tree

Leetcode-Easy 572. Subtree of Another Tree

作者头像
致Great
发布2018-04-11 16:32:14
6680
发布2018-04-11 16:32:14
举报
文章被收录于专栏:程序生活程序生活

572. Subtree of Another Tree

  • 描述: 给定两个二叉树s和t,判断t是否s的一个子树。要求结构完全一致
  • 思路: 递归
  • 代码
class Solution(object):
    def isSubtree(self, s, t):
        """
        :type s: TreeNode
        :type t: TreeNode
        :rtype: bool
        """
        def check(s, t):
            # helper function that does the actual subtree check
            if (s is None) and (t is None):
                return True
            if (s is None) or (t is None):
                return False
            return (s.val == t.val and check(s.left, t.left) and check(s.right, t.right))

        # need to do a pre-order traversal and do a check
        # for every node we visit for the subtree
        if not s:
            # return False since None cannot contain a subtree 
            return
        if check(s, t):
            # we found a match
            return True
        if self.isSubtree(s.left, t) or self.isSubtree(s.right, t):
            # a match was found
            return True
        return False
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.03.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 572. Subtree of Another Tree
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档