Invert Binary Tree is one of the most popular programming problems. It’s an easy problem. I assume that you have a basic understanding of Binary Tree and Recursion.
The problem description is straightforward. Simply put, we have to invert a binary tree and then return the root.
More precisely, to solve this, we need to swap the left subtree with the right subtree of a node. And we have to do this swapping in every step. We will solve this problem recursively. The algorithm we will use is DFS.
Let’s see the solution in Python.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if not root:
return None
left = self.invertTree(root.left)
right = self.invertTree(root.right)
root.left = right
root.right = left
return rootThe time complexity of this problem is O(n), where n is the number of nodes. And space complexity is also O(n). This n is the number stack size in the memory for recursive function calls.
