AlgoDaily Solution

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