zoukankan      html  css  js  c++  java
  • 剑指 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
    
  • 相关阅读:
    php 原生 好久不写原生demo了
    鸡汤
    php 发送smtp邮件
    php微信支付代码
    3、Flume
    P2761 软件补丁问题
    TQL
    二分图匹配
    p2597 灾难
    P3958 奶酪
  • 原文地址:https://www.cnblogs.com/fengcnblogs/p/13514743.html
Copyright © 2011-2022 走看看