Here is the interview question prompt, presented for reference.
Can you invert a binary tree
over its vertical axis? This is a famous problem made popular by this tweet:
Google: 90% of our engineers use the software you wrote (Homebrew), but you can’t invert a binary tree on a whiteboard so f**k off.— Max Howell (@mxcl) June 10, 2015
Given a binary tree
like this:
4
/ \
2 7
/ \ / \
1 3 6 9
Performing an inversion would result in:
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
The definition of a tree node is as follows:
function Node(val) {
this.val = val;
this.left = null;
this.right = null;
}
1000
-1000000000
and 1000000000
O(n)
O(logn)
You can see the full challenge with visuals at this link.
Challenges • Asked almost 7 years ago by Jake from AlgoDaily
This is the main discussion thread generated for Invert a Binary Tree.
Hey there,
Great exercise, thank you!
I wanted to point out the test case #3 is incorrect.
It defines inverted_tree2.right.left = Node(8) where it should actually be = Node(3).
As a consequence, my submission is failing that test and is not getting accepted.
Thank you!
Hi Andre,
Thanks for the heads up-- this is fixed!