Solution 1
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
#Recusive
if not root: return None
right = self.invertTree(root.left)
left = self.invertTree(root.right)
root.right = right
root.left = left
return root
Time complexity is O(n). Space complexity is O(n).
Solution 2
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def invertTree(self, root: TreeNode) -> TreeNode:
#Iterative
if not root: return None
current = root
stack = []
while stack or current:
if current:
stack.append(current)
current = current.left
else:
current = stack.pop()
current.right, current.left = current.left, current.right
current = current.left
return root
Time complexity is O(n). Space complexity is O(n).