繁体   English   中英

验证二进制搜索树-JavaScript

[英]validating a Binary Search Tree - JavaScript

我正在尝试编写一个验证二进制搜索树的函数。 我有一个可以正常工作以进行遍历并推送到数组的版本,但是我正在尝试也创建一个可以递归地跟踪最小值和最大值的版本。 我成功地传递了树,它检查了我的第一个checkBST函数中的第一个节点,但是在isValidBST函数中,递归调用从未发生,并且似乎每个节点都被视为null,我不确定为什么。 将不胜感激任何人的投入!

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));

当前代码中有一个容易遗漏但很重要的缺陷: isValidBST()应该递归到自身( isValidBST() )中,而不是递归到忽略节点参数之后的任何参数的checkBST()中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM