One Pager Cheat Sheet
- Write a method to
calculate the depthof abinary treeusingO(logn)time complexity andO(n)space complexity. - We can traverse the
binary treeto count itsmaximum levelsby navigating two children at each node and detecting aleafwhen aleftorrightdoes not exist. - We can
returnwhen there is nonodepresent. - We can recursively traverse down the left and right children of each node until we reach a leaf,
returningthe number of levels traversed and with a time complexity of O(log n).
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 howDeep(root) { if (root === null) { return 0; }​ return Math.max(howDeep(root.left), howDeep(root.right)) + 1;}​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);​// Binary search treesvar tree3 = new Node(6);tree3.left = new Node(3);​var tree4 = new Node(5);OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment
You're doing a wonderful job. Keep going!
If you had any problems with this tutorial, check out the main forum thread here.

