In a quiz for my Javascript class, we were told to make a simple tree and write a function that returns true or false whether it is a BST or not.
I got a decent grade, but i got 10 points off because the instructor said "It can be done in 6 less lines".
This is what I had:
function node(value, left, right){
this.Value = value;
this.Left = left;
this.Right = right;
}
//this IS a BST, returns true
var head = new node(8, new node(9, null, null), new node(10, new node(9, null, null), new node(14, new node(13, null, null), null)));
function isBST(currNode){
if(currNode.Left === null && currNode.Right === null){
return true;
}
else if(currNode.Left.Value > currNode.Value || currNode.Right.Value < currNode.Value){
return false;
}
else{
if(currNode.Left === null){
return isBST(currNode.Right);
}
else if(currNode.Right === null){
return isBST(currNode.Left);
}
else{
return (isBST(currNode.Left) && isBST(currNode.Right));
}
}
}
console.log(isBST(head));
Anything I'm overlooking here? Maybe it shouldn't have been recursive?
elsecondition is unreachable though.