var displayTree = (tree) => console.log(JSON.stringify(tree, null, 2));
function Node(value) {
this.value = value;
this.left = null;
this.right = null;
}
function isBinarySearchTree(tree) {
// Only change code below this line
function isBinarySubTree(node){
//no node
if (node == null) return true;
//left node check
if (node.left && node.left.value > node.value) return false;
//right node check
if (node.right && node.right.value < node.value) return false;
//recursion for further children
if (node.left && !isBinarySearchTree(node.left) || node.right && !isBinarySearchTree(node.right))
return false;
return true;
}
//passing root node
return isBinarySubTree(tree.root)
// Only change code above this line
}
So I tested this by creating an add node method and passing a non binary tree and a binary tree, alongwith the no root node and single root node cases. The output comes out correct in console. But I am unable to pass test.
Nodes have at most 2 child nodes (placed to the right and/or left) based on if the child node’s value is greater than or equal to (right) or less than (left) the parent node.
I think that the equal goes on the left when you negate these expressions.
Though, I was wondering about a general query in regards to binary tree - As it goes, all left child nodes are small that parent and right nodes are greater than parent. But if it’s equal then It can only go to right or left - So, is there a standard for it - or is it just defined differently according to whoever is using it?
I’m not aware of a specific convention. Since a user wouldn’t directly touch the internals of your tree, I probably doesn’t make a huge difference which one you pick.