javascript - 在js中获取二叉搜索树的最大值

标签 javascript data-structures

我正在观看来自 udemy 的关于二进制搜索树的 JS 数据结构视频。我们有一种通过递归找到最大值的方法。

我想更多的是比较所有的数字,比如

BST.prototype.getMaxVal = function() {
  let num = null;
  if (num === null) num = this.value;
  else if (this.value > num) num = this.value;
  if (this.left) return this.left.getMaxVal();
  return num;
}

但答案是

BST.prototype.getMaxVal = function() {
  if (this.right) return this.right.getMaxVal();
  else return this.value;
}

105 是最后一个没有自己叶子的数字,但是这个方法找到它之前的 107?它如何在没有任何比较逻辑的情况下找到它?

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

BST.prototype.insert = function(value) {
  if (value <= this.value) {
    if (!this.left) this.left = new BST(value);
    else this.left.insert(value);
  } else {
    if (!this.right) this.right = new BST(value);
    else this.right.insert(value);
  }

  return this;
}


const bst = new BST(50); 

bst.insert(30);
bst.insert(70);
bst.insert(107);
bst.insert(60);
bst.insert(59);
bst.insert(20);
bst.insert(45);
bst.insert(35);
bst.insert(85);
bst.insert(105);
bst.insert(10);

bst.getMaxVal();

https://repl.it/repls/NumbYellowgreenPlans

最佳答案

所以这是 BST 的可视化表示。如果某个值小于你,你把它传到左边,让左边的子BST决定放在哪里。如果某个值比你大,就把它传递给正确的子 BST,让它决定把值放在哪里。

enter image description here

在这个设置中,保证在最左边的叶子上,它必须是最小值,而在最右边的叶子上,它必须包含最大值。所以,思路就是,从每一个BST来看,要么他的左树什么都没有,要么它的值一定比我小。所以算法写道:

BST.prototype.getMinVal = function() {
  // if left tree is not null, it must be smaller tha me. Return its value
  if (this.left) return this.left.getMinVal();
  // if left tree is null, indicate i'm the smallest available, return me instead.
  else return this.value;
}

更新 1

有一点需要注意。 BST 就是为了达到这样的目的而设计的。它的数据在进行插入时被结构化以避免遍历整棵树的需要。它的值是有序的,因此在查找最小/最大值时不必遍历每个节点。如果你的算法需要,你没有正确使用它,即使函数产生了正确的逻辑输出。

关于javascript - 在js中获取二叉搜索树的最大值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51699579/

相关文章:

javascript - 使用 ContextAPI 不会重新呈现其使用者,但内容已更改。为什么?

javascript - 如何为同一个键设置多个值而不覆盖以前的值?

javascript - 与非 Javascript 服务器相比,使用基于 Javascript 的服务器有哪些优势?

algorithm - 如何检查循环单链表是否为回文?

c++ - 图中最大独立集的递归程序

ie7 中的 JavaScript 错误

javascript - 未捕获的类型错误打开对话框

algorithm - 给定 IP 范围和映射的平面文件,找到给定 IP 的城市

algorithm - 关于 Bellman Ford 算法的旧考试,需要点子吗?

algorithm - 用于在类别的二维网格中搜索坐标的最佳数据结构