zoukankan      html  css  js  c++  java
  • 101. 对称二叉树

    问题描述

    给定一个二叉树,检查它是否是镜像对称的。

    例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

        1
       / 
      2   2
     /  / 
    3  4 4  3
    

    但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:

        1
       / 
      2   2
          
       3    3
    

    解决方案

    递归:

    class Solution:
        def isSymeetric(self, root):
            if root is None:
                return True
            else:
                return self.isMirror(root.left, root.right)
    
        def isMirror(self, left, right):
            if left is None and right is None:
                return True
            if left is None or right is None:
                return False
            if left.val == right.val:
                outPair = self.isMirror(left.left, right.right)
                inPair = self.isMirror(left.right, right.left)
                return outPair and inPair
            else:
                return False
    

    迭代:

    class Solution:
        def isSymmetric(self, root):
            if root is None:
                return True
    
            stack = [[root.left, root.right]]
    
            while len(stack) > 0:
                pair = stack.pop(0)
                left = pair[0]
                right = pair[1]
    
                if left is None and right is None:
                    continue
                if left is None or right is None:
                    return False
                if left.val == right.val:
                    stack.insert(0, [left.left, right.right])
    
                    stack.insert(0, [left.right, right.left])
                else:
                    return False
            return True
    
    
  • 相关阅读:
    一、【注解】Spring注解@ComponentScan
    一致性Hash算法
    垃圾回收器搭配和调优
    JVM的逃逸分析
    简单理解垃圾回收
    类加载机制和双亲委派模型
    VMWare15下安装CentOS7
    HBase协处理器(1)
    依赖注入的三种方式
    Javascript-设计模式_装饰者模式
  • 原文地址:https://www.cnblogs.com/huang-yc/p/10753828.html
Copyright © 2011-2022 走看看