LeetCode題解(Offer26):判斷二叉樹A是否為二叉樹B的子樹(Python)

長行發表於2020-10-01

題目:原題連結(中等)

標籤:樹、二叉樹、深度優先搜尋

解法時間複雜度空間複雜度執行用時
Ans 1 (Python) O ( N × H ) O(N×H) O(N×H) O ( N × H ) O(N×H) O(N×H)112ms (94.89%)
Ans 2 (Python)
Ans 3 (Python)

解法一(深度優先搜尋):

class Solution:
    def __init__(self):
        self.ans = False

    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        if not A or not B:
            return False

        def dfs1(a):
            if a:
                if a.val == B.val:
                    if dfs2(a.left, B.left) and dfs2(a.right, B.right):
                        self.ans = True
                dfs1(a.left)
                dfs1(a.right)

        def dfs2(a, b):
            if a and b:
                return a.val == b.val and dfs2(a.left, b.left) and dfs2(a.right, b.right)
            elif a:
                return True
            elif b:
                return False
            else:
                return True

        dfs1(A)

        return self.ans

相關文章