226. Invert Binary Tree

226. Invert Binary Tree

Leetcode Blind 75

12th Sept 2022 ~ Dion Pinto

Description

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

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 not root:
                return 
            
            temp = root.left
            root.left=root.right
            root.right=temp
            
            self.invertTree(root.left)
            self.invertTree(root.right)

            return root
							
			

Time Complexity => o(n)

Space Complexity => o(n) (height of tree)

Back