swift递归检测对称二叉树

40次阅读

共计 372 个字符,预计需要花费 1 分钟才能阅读完成。


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)
}

正文完
 0