3.2 KiB
3.2 KiB
id, title, challengeType, forumTopicId
id | title | challengeType | forumTopicId |
---|---|---|---|
5cc0c1b32479e176caf3b422 | Check if Tree is Binary Search Tree | 1 | 301624 |
Description
Instructions
isBinarySearchTree
which takes a tree as an input and returns a boolean value for whether the tree is a binary search tree or not. Use recursion whenever possible.
Tests
tests:
- text: Your Binary Search Tree should return true when checked with <code>isBinarySearchTree()</code>.
testString: assert((function() { var test = false; if (typeof BinarySearchTree !== 'undefined') { test = new BinarySearchTree() } else { return false; }; test.push(1); test.push(5); test.push(3); test.push(2); test.push(4); return isBinarySearchTree(test) == true})());
Challenge Seed
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
}
function isBinarySearchTree(tree) {
// Only change code below this line
// Only change code above this line
}
After Test
BinarySearchTree.prototype.push = function(val) {
var root = this.root;
if (!root) {
this.root = new Node(val);
return;
}
var currentNode = root;
var newNode = new Node(val);
while (currentNode) {
if (val < currentNode.value) {
if (!currentNode.left) {
currentNode.left = newNode;
break;
} else {
currentNode = currentNode.left;
}
} else {
if (!currentNode.right) {
currentNode.right = newNode;
break;
} else {
currentNode = currentNode.right;
}
}
}
};
Solution
var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function BinarySearchTree() {
this.root = null;
}
function isBinarySearchTree(tree) {
if (tree.root == null) {
return null;
} else {
let isBST = true;
function checkTree(node) {
if (node.left != null) {
const left = node.left;
if (left.value > node.value) {
isBST = false;
} else {
checkTree(left);
}
}
if (node.right != null) {
const right = node.right;
if (right.value < node.value) {
isBST = false;
} else {
checkTree(right);
}
}
}
checkTree(tree.root);
return isBST;
}
};