Invert Binary Tree (Leetcode 226)
It is also called as Mirror of a Binary Tree. Technique: FAITH technique of Recursion
Problem Link 1: https://leetcode.com/problems/invert-binary-tree/
Problem Link 2: https://practice.geeksforgeeks.org/problems/mirror-tree/1
Recursive Approach:
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
if(root is None):
return None
l=self.invertTree(root.left)
r=self.invertTree(root.right)
root.left=r
root.right=l
return root
Iterative Approach (Using Stack):
class Solution:
def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
s=[root]
while(len(s)>0):
node=s.pop()
if(node is not None):
node.left,node.right=node.right,node.left
s.append(node.left)
s.append(node.right)
return root
Last updated