LeetCode – 226. Invert Binary Tree

題目連結: https://leetcode.com/problems/invert-binary-tree/

法ㄧ(Recursive version):

func invertTree(_ root: TreeNode?) -> TreeNode? {
    if root != nil {
        let tmp = root?.left
        root?.left = root?.right
        root?.right = tmp
        _ = invertTree(root?.left)
        _ = invertTree(root?.right)
    }
    return root
}

法二(Iterative version):

    func invertTree(_ root: TreeNode?) -> TreeNode? {
        if root == nil { return root }
        var stack: [TreeNode] = []
        stack.append(root!)
        while !stack.isEmpty {
            let node = stack.removeLast()
            let tmp = node.left
            node.left = node.right
            node.right = tmp
            if let left = node.left {
                stack.append(left)
            }
            if let right = node.right {
                stack.append(right)
            }
        }
        return root
    }