首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >验证二进制搜索树- JavaScript

验证二进制搜索树- JavaScript
EN

Stack Overflow用户
提问于 2015-11-17 08:29:20
回答 1查看 675关注 0票数 0

我正在尝试编写一个函数来验证二进制搜索树。我让一个版本按顺序遍历并推送到数组,但我也尝试做一个版本,您可以递归地跟踪min和max。我正在成功地传递树,它检查我的第一个checkBST函数中的第一个节点,但是在isValidBST函数中,递归调用永远不会发生,似乎每个节点都被视为null,我不知道为什么。将感谢任何人的投入!

代码语言:javascript
代码运行次数:0
运行
复制
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));
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-11-17 08:56:23

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

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33752251

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档