树的子结构(1)

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None
#先是比较树根左右边的是否相等。如果没有在进入三角处理。
class Solution:
    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        if A == None or B == None:
            return False
        return self.dfs(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right,B)
    
    def dfs(self, A: TreeNode, B: TreeNode) -> bool:
        if B == None:
            return True
        if A == None:
            return False
        return A.val == B.val and self.dfs(A.left,B.left) and self.dfs(A.right,B.right)


作者:mu-qian-ruo-chi
链接:https://leetcode-cn.com/problems/shu-de-zi-jie-gou-lcof/solution/pythondi-gui-shen-du-you-xian-sou-suo-by-mu-qian-r/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        def recur(A, B):
            if not B: return True
            if not A or A.val != B.val: return False
            return recur(A.left, B.left) and recur(A.right, B.right)

        return bool(A and B) and (recur(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B))

        

猜你喜欢

转载自www.cnblogs.com/topass123/p/12770939.html