Solving the infamous “inverting a binary tree” problem

This tweet initially drew a lot of attention because:
1/ It’s about the Google interview process.
2/ The problem “invert a binary tree” sounds tricky and obscure.
3/ It’s from a well-known individual within the developer community.
To be clear, this post is about how to solve the problem. While I agree that perhaps asking this question may not have been appropriate for someone in this situation (writing such a popular library), I also don’t think this question isn’t as scary as it might sound. Let’s break it down!
Tree questions almost always use recursion, which makes sense — we need to be able to execute some code on a particular node and its children (which can be accessed via `node.right` and `node.left`).
I’ll break this down into steps, which I’ll then map to a corresponding comment in the code. My mental model is to always think — if given a particular node, what would I want to do with it?
1/ The first case to think about is a base case — what should I do if the node doesn’t exist? Well, if there isn’t anything to “invert”, I’ll just return the node. Pretty straightforward.
2/ If the node *does* exist, what should I do with its children (node.left and node.right)? “Invert” just means the left child should be the right child and vice versa, so it’s as simple as:
node.left, node.right = node.right, node.left
(Python has a nice one-liner for swapping variables.)
3/ Now, I want to apply the exact same logic to the children! So, I’ll call my function on node.left and node.right.
And that’s literally it! A subtlety — what if node.left or node.right doesn’t exist? Recognize that’s *already covered* by your base case — we’ll just return the node which is None!
So we’ll introduce a helper that we can call on each node, then call that helper on the root, and return that value.

You can submit your code here to test it out: https://leetcode.com/problems/invert-binary-tree/
Let me know if you have any questions below or want me to write about any other coding questions!
For more articles like this, follow me on Medium. Not a member yet? Join the community. Want more software engineering interview guides and coding question tips? Check out all of my writing organized by topic in this article.
If you have any requests for what I should write, please let me know!






