乐趣区

swift迭代检测对称二叉树



func isSymmetric(_ root: TreeNode?) -> Bool {
    guard let root = root else {return true}
    var queue1: [TreeNode] = []
    var queue2: [TreeNode] = []
    queue1.append(root)
    queue2.append(root)
    while queue1.count > 0 {let left = queue1.removeFirst()
        let right = queue2.removeFirst()
        if left.val != right.val {return false}
        let i = left.left
        let j = left.right
        let x = right.left
        let y = right.right
        if i == nil && y != nil || i != nil && y == nil {return false}
        if j == nil && x != nil || j != nil && x == nil {return false}
        if i != nil && y != nil {queue1.append(i!)
            queue2.append(y!)
        }
        if j != nil && x != nil {queue1.append(j!)
            queue2.append(x!)
        }
    }
    return true
}

退出移动版