AlgoDaily Solution

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

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.

Returning members can login to stop seeing this.

JAVASCRIPT
OUTPUT
Results will appear here.