One Pager Cheat Sheet
- We can invert a
binary tree
over its vertical axis, resulting in the reversing of the node values between the left and right subtrees, with a time complexity ofO(n)
and space complexity ofO(logn)
. - Max Howell's misfortune in getting an infamous Google Interview question wrong reminds us to revert to the basics of
brute force
when confronted with a challenging problem. - We
swap
thekey values
of successive rows to invert a binary tree vertically. - The process of
swapping
two nodes with more than one node per level could result in the inversion of a binary tree. - By swapping
4
and5
, followed by swapping5 -> 4
and3
, we can get3 -> 5 -> 4
to correctly invert the binary tree. - We can swap the left and right nodes at each iteration by either a recursive stack solution or a queue BFS technique, resulting in an
O(n)
time andO(logn)
space complexity.
This is our final solution.
To visualize the solution and step through the below code, click Visualize the Solution on the right-side menu or the VISUALIZE button in Interactive Mode.
xxxxxxxxxx
70
}
var assert = require('assert');
โ
function invertTree(head) {
if (head) {
var temp = head.left;
head.left = head.right;
head.right = temp;
โ
invertTree(head.left);
invertTree(head.right);
}
โ
return head;
}
โ
function Node(val) {
this.val = val;
this.left = null;
this.right = null;
}
โ
// Regular binary trees
var tree1 = new Node(4);
tree1.left = new Node(1);
tree1.right = new Node(3);
โ
var tree2 = new Node(5);
tree2.left = new Node(10);
tree2.left.left = new Node(17);
tree2.left.right = new Node(3);
tree2.right = new Node(8);
โ
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
Great job getting through this. Let's move on.
If you had any problems with this tutorial, check out the main forum thread here.