Posts

Showing posts with the label Google

Invert Binary

Image
Invert a binary tree. Example: Input: 4 / \ 2 7 / \ / \ 1 3 6 9 Output: 4 / \ 7 2 / \ / \ 9 6 3 1 Trivia: This problem was inspired by  this original tweet  by  Max Howell : Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f*** off. I hope, you understand the above problem where we need to just invert the complete binary tree. While analyzing the problem, I found that we need some kind of storage where we can push elements using FIFO- First In First Out approach. We can say that it can be achieved using the queue data structure. We will push the root in the queue and iterate until the queue becomes empty. We poll/pop the node from the queue and swap it's left and right child and again push the left and right child into the queue itself. This process will happen until the queue is empty. Note: We are not going to push the node which is null.