乐趣区

swift递归检测对称二叉树


var isS: Bool = true

func isSymmetric(_ root: TreeNode?) -> Bool {helper(root, root)
    return isS
}

func helper(_ left: TreeNode?, _ right: TreeNode?) {
    if isS == false {return}
    if left == nil {
        isS = right == nil
        return
    }
    if right == nil {
        isS = left == nil
        return
    }
    if left!.val != right!.val {
        isS = false
        return
    }
    
    let nodei = left?.left
    let nodej = left?.right
    let nodex = right?.left
    let nodey = right?.right

    helper(nodei, nodey)
    helper(nodej, nodex)
}
退出移动版