0

I'm trying to write a function that validates a binary search tree. I got a version working where I do in order traversal and push to an array, but I'm trying to also do a version where you keep track of the min and max recursively. I am successfully passing in the tree and it checks the first node in my first checkBST function, but in the isValidBST function, the recursive calls never happen and it seems like every node is treated as null and I'm not sure why. Will appreciate anyones input!

function BinarySearchTree(value) {
  this.val = value;
  this.left = null;
  this.right = null;
}

//insert

BinarySearchTree.prototype.insert = function (toInsert) {

  if (this.val > toInsert) {
    if (this.left === null) {
      this.left = new BinarySearchTree(toInsert);
    } else {
      this.left.insert(toInsert);
    }
  }

  if (this.val < toInsert) {
    if (this.right === null) {
      this.right = new BinarySearchTree(toInsert);
    } else {
      this.right.insert(toInsert);
    }
  }
};


function checkBST(node) {
  // console.log(node.right);
  return isValidBST(node, null, null);
}

function isValidBST(node, min, max) {
  // console.log(min, max);

  //this keeps getting called
  if (node === null) {
    console.log("CHECKING NULL");
    return true;
  }
  // this doesn't get called, which is good 
  if ((min !== null && node.val > max) || (max !== null && node.val < min)) {
    console.log("CHECKING NODE VALUES in false", node.val);
    return false;
  }
  //these calls are never entered.
  if (!checkBST(node.left, min, node.val) || !checkBST(node.right, node.val, max)) {
    console.log("CHECKING NODE VALUES in recursive call", node.val);
    return false;
  }
  return true;
}



var bst = new BinarySearchTree(7);
bst.insert(9);
bst.insert(6);
bst.insert(4);


console.log(checkBST(bst));
2
  • Looks like isValidBST() is supposed to recurse into itself (isValidBST()), not into checkBST() which is ignoring any parameters after the node parameter. Commented Nov 17, 2015 at 8:44
  • 1
    wow, thanks - can't believe I missed that. please post as an answer so I can accept and you can get the points you deserve :) Commented Nov 17, 2015 at 8:49

1 Answer 1

2

There is an easy to miss but important flaw in the current code: isValidBST() is supposed to recurse into itself (isValidBST()), not into checkBST() which is ignoring any parameters after the node parameter.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.