Invert binary tree
July 14, 2022
treeProblem URL: Invert binary tree
We can take the left subtree and right subtree and swap their position. We will do it recursively for every subtree.
# 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 root
root.left, root.right = root.right, root.left
self.invertTree(root.left)
self.invertTree(root.right)
return root
Time Complexity: O(n)
Space Complexity: O(n)