At every node, we can recursively traverse down the left and right children if they exist, until we reach a leaf.
The difficult part is keeping track of the number of levels.
To do that, we can make the return statement the number of levels thus far, and increment it by 1 at every step.
This solution has a time complexity O(log n).
xxxxxxxxxx68
console.log('PASSED: ' + 'assert.deepEqual(howDeep(tree1), 2);');var assert = require('assert');function howDeep(root) { // Fill in this method return root;}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);OUTPUT
Results will appear here.