剑指 Offer 26. 树的子结构

思路

  1. dfs
    注意注释掉的代表完全子树
class Solution:
    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        def helper(a, b):
            # if not a and not b:
            #     return True
            # if not a and b:
            #     return False
            # if a and not b:
            #     return False
            if not b:
                return True
            if not a:
                return False
            if a.val == b.val:
                return helper(a.left, b.left) and helper(a.right, b.right)
            else:
                return False
        if not B or not A:
            return False
        return helper(A, B) or self.isSubStructure(A.left, B) or self.isSubStructure(A.right, B)
  1. 迭代
class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return 
        stack = [root]
        while stack:
            cur = stack.pop()
            if cur.left:
                stack.append(cur.left)
            if cur.right:
                stack.append(cur.right)
            cur.left, cur.right = cur.right, cur.left
        return root
posted @ 2020-08-16 22:20  珊珊来迟0  阅读(67)  评论(0编辑  收藏  举报