Coding Easy Software Engineer Full Stack Backend

Given the root of a binary tree, invert the tree and return its root (Invert Binary Tree).

Practise this question with AI feedback

Record your spoken answer or type your response to receive immediate scoring and STAR improvements.

💡 Suggested Approach & Sample Answer

Optimal Recursive / Depth-First Search Approach:
- Recursively swap the left and right child pointers for every node in the binary tree.

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def invert_tree(root: TreeNode) -> TreeNode:
if not root:
return None
# Swap left and right children
root.left, root.right = root.right, root.left
# Recurse down subtrees
invert_tree(root.left)
invert_tree(root.right)
return root

Complexity & Key Logic:
- Time Complexity: O(N) visiting each of the N nodes exactly once.
- Space Complexity: O(H) call stack space, where H is tree height (O(log N) for balanced trees, O(N) for degenerate trees).
- Algorithm Details:
- Base Case: If node is None, return None.
- Swap current node's left and right pointers.
- Recursively invert the newly swapped subtrees.
- Return original root node.

🎯 What Interviewers Listen For

How would you answer this in a real interview?

Use our free AI mock practice tool to test your response, analyze speaking pacing, and refine your STAR structure.

🔗 Related Coding Questions