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)
    }
}
原文地址:https://www.cnblogs.com/huangzs/p/14037313.html