4. Trees and Tries

Table of Contents

226. Invert Binary Tree

Given the root of a binary tree, invert the tree, and return its root.

Image from https://leetcode.com/problems/invert-binary-tree/
Image from https://leetcode.com/problems/invert-binary-tree/
Key Ideas
Code


# 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 root is None or root.left == None and root.right == None:
            return root

        root.left, root.right = root.right, root.left
        self.invertTree(root.left)
        self.invertTree(root.right)

        return root

Previous
Next