FresherFresher (0–1 yrs)CodingPythonGoogleAmazon
Invert Binary Tree
Invert a binary tree by swapping every left and right child, and return the root.
Answers use simple, clear English.
Time: O(n)Space: O(h)
Quick interview answer
Recursively swap children then invert subtrees (or BFS/DFS iteratively swapping at each node). Post-order or pre-order both work if you swap before/after consistently.
Detailed answer
Recursively swap children then invert subtrees (or BFS/DFS iteratively swapping at each node). Post-order or pre-order both work if you swap before/after consistently. Famous warm-up; interviewers often follow with serialize/deserialize.
Full explanation
Famous warm-up; interviewers often follow with serialize/deserialize.
Real example & use case
Mirroring a UI layout tree for RTL language support.
Pros & cons
Pros: O(n) clear. Cons: mutates in place — clone if immutability required.
Code example
def invert_tree(root):
if not root:
return None
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return rootPractice code · python (view only · no execution)
def invert_tree(root):
if not root:
return None
root.left, root.right = invert_tree(root.right), invert_tree(root.left)
return root#tree#recursion