leetcode-572-另一个树的子树

题目描述:

 

 方法一:DFS枚举 O(s*t)  O(max(ds,dt)   d代表深度

class Solution:
    def isSubtree(self, s: TreeNode, t: TreeNode) -> bool:
        def isSameTree(s, t):
            if not s and not t:
                return True
            if not s or not t:
                return False
            return s.val == t.val and isSameTree(s.left, t.left) and isSameTree(s.right, t.right)

        if not s and not t:
            return True
        if not s or not t:
            return False
        return isSameTree(s, t) or self.isSubtree(s.left, t) or self.isSubtree(s.right, t)

方法二:dfs转序列 + 判断子串算法(kmp等)O(s+t)

 

posted @ 2020-05-07 16:15  oldby  阅读(128)  评论(0编辑  收藏  举报