DEV Community

Akhil
Akhil

Posted on

Invert Binary Tree - Google interview question

"You developed an app which has over a million downloads, that's cute! But can you invert a binary tree "?

Alt Text

Question: Invert a Binary Tree.

What's meant by "Invert Binary Tree ?"

It means for each node, the left-subtree of the node becomes the right-subtree and right-subtree becomes left-subtree.

Let's simplify the question step by step:

Step 1 > How to traverse the tree?
Aim : Our main aim is to:
1> visite each node.
2> swap left subtree and right subtree.
3> go deep in the respective subtree and repeat.

So it makes sense to use DFS in this case.

Step 2> How do we swap?
1> we could simply swap the sub-trees using a temporary container.

Let's visualize this :

Alt Text

Let's write some code :

var invertTree = function(root) {
    return dfs(root);
};

function dfs(root){
    if(root == null) return null;
    let temp = root.left;
    root.left = root.right;
    root.right = temp;
    dfs(root.left);
    dfs(root.right);
    return root;
}

Enter fullscreen mode Exit fullscreen mode

That's it !, now you know how to solve a question which is frequently asked at google!

github : https://github.com/AKHILP96/Data-Structures-and-Algorithms/blob/master/problems/invertBinaryTree.js

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay