@hotea,

Interesting. Your iterative solution is iterative in-order DFS, and @StefanPochmann 's version is iterative pre-order DFS, while I first thought about iterative post-order DFS as an attempt of direct translation of the short recursive post-order. Apparently, all three versions work for this problem. In the recursive world, those would be:

# Pre-order
if not root:
return root
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
# In-order
if not root:
return root
self.invertTree(root.left)
root.left, root.right = root.right, root.left
self.invertTree(root.left)
return root
# Post-order (this is the longer version of @StefanPochmann 's first solution)
if not root:
return root
self.invertTree(root.left)
self.invertTree(root.right)
root.left, root.right = root.right, root.left
return root

The first two recursive solutions don't allow for recursive calls to be compressed into one line, but post-order version does, so it is preferable.

Since in-, pre- and post-order recursive traversals can all be converted into their respective iterative forms, any one of those will work, but from the iterative implementation logic pre-order is easier than in-order and in-order is in turn easier than post-order, so if we need an iterative solution, it would make sense for us to choose the iterative pre-order in an interview, which Stefan did here in his explicit stack solution. I personally prefer though to maintain an invariant of no None's in the stack, since it saves on number of append calls and while loop iterations at the expense of if checks which are cheaper, so I usually do this:

if not root:
return None
stack = [root]
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left #specific to this problem
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return root