Leetcode-Easy 572. Subtree of Another Tree

时间:2022-05-08
本文章向大家介绍Leetcode-Easy 572. Subtree of Another Tree,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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