zoukankan      html  css  js  c++  java
  • LeetCode对称二叉树Swift

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

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

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

    思路:递归判断某个结点的左子树和右子树是否成镜像

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     public var val: Int
     *     public var left: TreeNode?
     *     public var right: TreeNode?
     *     public init(_ val: Int) {
     *         self.val = val
     *         self.left = nil
     *         self.right = nil
     *     }
     * }
     */
    class Solution {
        func isSymmetric(_ root: TreeNode?) -> Bool {
            return isMirrorTree(root?.left, root?.right)
        }
        func isMirrorTree(_ nodeL: TreeNode?, _ nodeR: TreeNode?) -> Bool {
            if nodeL == nil && nodeR == nil {
                return true
            }
    
            if nodeL == nil || nodeR == nil {
                return false
            } 
    
            guard nodeL?.val == nodeR?.val else {
                return false
            }
    
            return isMirrorTree(nodeL?.left, nodeR?.right) && isMirrorTree(nodeL?.right, nodeR?.left)
        }
    }
  • 相关阅读:
    生成器,生成器表达式。
    device busy
    memcached
    ps f
    Eviews9.0---软件安装
    免费提取百度文库 doc 文件
    Matlab---length函数
    Matlab 路径函数
    matlab中disp函数的简单用法
    MATLAB---dir函数
  • 原文地址:https://www.cnblogs.com/huangzs/p/14037313.html
Copyright © 2011-2022 走看看