Invert Binary Tree

Tree
https://leetcode.com/problems/invert-binary-tree

# Solution

Let nn be the number of nodes in the tree.

All following solutions take O(n)O(n) time and O(logn)O(\log n) space.

# Brute Force

def invertTree(self, root: TreeNode) -> TreeNode:
    if not root:
        return root
    root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
    return root
1
2
3
4
5
def invertTree(self, root: TreeNode) -> TreeNode:
    if not root:
        return
    root.left, root.right = root.right, root.left
    self.invertTree(root.left)
    self.invertTree(root.right)
    return root
1
2
3
4
5
6
7
    def invertTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return
        self.invertTree(root.left)
        self.invertTree(root.right)
        root.left, root.right = root.right, root.left
        return root
1
2
3
4
5
6
7