AlgoDaily Solution
1var assert = require('assert');
2
3function howDeep(root) {
4 if (root === null) {
5 return 0;
6 }
7
8 return Math.max(howDeep(root.left), howDeep(root.right)) + 1;
9}
10
11function Node(val) {
12 this.val = val;
13 this.left = null;
14 this.right = null;
15}
16
17// Regular binary trees
18var tree1 = new Node(4);
19tree1.left = new Node(1);
20tree1.right = new Node(3);
21
22var tree2 = new Node(5);
23tree2.left = new Node(10);
24tree2.left.left = new Node(17);
25tree2.left.right = new Node(3);
26tree2.right = new Node(8);
27
28// Binary search trees
29var tree3 = new Node(6);
30tree3.left = new Node(3);
31
32var tree4 = new Node(5);
33tree4.left = new Node(3);
34tree4.left.left = new Node(2);
35tree4.left.left.left = new Node(1);
36
37var tree5 = new Node(8);
38tree5.left = new Node(6);
39tree5.right = new Node(9);
40tree5.left.left = new Node(5);
41tree5.left.right = new Node(7);
42tree5.right.right = new Node(10);
43
44try {
45 assertIsFunction(howDeep, '`howDeep` should be a function');
46
47 console.log('PASSED: ' + '`howDeep` should be a function');
48} catch (err) {
49 console.log(err);
50}
51
52try {
53 assert.deepEqual(howDeep(tree1), 2);
54
55 console.log('PASSED: ' + 'assert.deepEqual(howDeep(tree1), 2);');
56} catch (err) {
57 console.log(err);
58}
59
60try {
61 assert.deepEqual(howDeep(tree4), 4);
62
63 console.log('PASSED: ' + 'assert.deepEqual(howDeep(tree4), 4);');
64} catch (err) {
65 console.log(err);
66}
67
68function assertIsFunction(f) {
69 return typeof f === 'function';
70}
Community Solutions
Community solutions are only available for premium users.
Access all course materials today
The rest of this tutorial's contents are only available for premium members. Please explore your options at the link below.
xxxxxxxxxx
68
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 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);
// Binary search trees
var tree3 = new Node(6);
tree3.left = new Node(3);
OUTPUT
Results will appear here.