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
    
    
  • 相关阅读:
    三元表达式
    迭代器
    python字符串内的自建函数 string.
    shell下的while和if
    正则表达
    nginx下同时做负载均衡和web服务
    nfs匹配nginx服务
    yum安装nginx的负载均衡详解
    samba实战讲解
    python基础之数据类型
  • 原文地址:https://www.cnblogs.com/huang-yc/p/10753828.html
Copyright © 2011-2022 走看看