One Pager Cheat Sheet
- We can invert a
binary treeover 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 forcewhen confronted with a challenging problem. - We
swapthekey valuesof successive rows to invert a binary tree vertically. - The process of
swappingtwo nodes with more than one node per level could result in the inversion of a binary tree. - By swapping
4and5, followed by swapping5 -> 4and3, we can get3 -> 5 -> 4to 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.
xxxxxxxxxx70
}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 treesvar 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
Alright, well done! Try another walk-through.
If you had any problems with this tutorial, check out the main forum thread here.


