AlgoDaily Solution

1var assert = require('assert');
2
3function lowestCommonAncestor(root, node1, node2) {
4 if (root.val > node1 && root.val > node2) {
5 return lowestCommonAncestor(root.left, node1, node2);
6 } else if (root.val < node1 && root.val < node2) {
7 return lowestCommonAncestor(root.right, node1, node2);
8 } else {
9 return root.val;
10 }
11}
12
13function Node(val) {
14 this.val = val;
15 this.left = null;
16 this.right = null;
17}
18
19// Regular binary trees
20var tree1 = new Node(4);
21tree1.left = new Node(1);
22tree1.right = new Node(3);
23
24var tree2 = new Node(5);
25tree2.left = new Node(10);
26tree2.left.left = new Node(17);
27tree2.left.right = new Node(3);
28tree2.right = new Node(8);
29
30// Binary search trees
31var tree3 = new Node(6);
32tree3.left = new Node(3);
33
34var tree4 = new Node(5);
35tree4.left = new Node(3);
36tree4.left.left = new Node(2);
37tree4.left.left.left = new Node(1);
38
39var tree5 = new Node(8);
40tree5.left = new Node(6);
41tree5.right = new Node(9);
42tree5.left.left = new Node(5);
43tree5.left.right = new Node(7);
44tree5.right.right = new Node(10);
45
46try {
47 assertIsFunction(
48 lowestCommonAncestor,
49 '`lowestCommonAncestor` should be a function'
50 );
51
52 console.log('PASSED: ' + '`lowestCommonAncestor` should be a function');
53} catch (err) {
54 console.log(err);
55}
56
57try {
58 assert.equal(lowestCommonAncestor(tree4, 1, 3), 3);
59
60 console.log(
61 'PASSED: ' + 'assert.equal(lowestCommonAncestor(tree4, 1, 3), 3)'
62 );
63} catch (err) {
64 console.log(err);
65}
66
67try {
68 assert.equal(lowestCommonAncestor(tree5, 5, 10), 8);
69
70 console.log(
71 'PASSED: ' + 'assert.equal(lowestCommonAncestor(tree5, 5, 10), 8)'
72 );
73} catch (err) {
74 console.log(err);
75}
76
77function assertIsFunction(f) {
78 return typeof f === 'function';
79}
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
75
var assert = require('assert');
function lowestCommonAncestor(root, node1, node2) {
// 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.