javascript - 如何查找二叉树中是否存在值

标签 javascript html servlets

请有人告诉我如何查找二叉树中是否存在值? 我想查找二叉树的左节点或右节点中存在值吗?

BinarySearchTree.prototype = {

  //more code

  contains: function(value){
    var found       = false,
        current     = this._root

    //make sure there's a node to search
    while(!found && current){

      //if the value is less than the current node's, go left
      if (value < current.value){
        current = current.left;

        //if the value is greater than the current node's, go right
      } else if (value > current.value){
        current = current.right;

        //values are equal, found it!
      } else {
        found = true;
      }
    }

    //only proceed if the node was found
    return found;
  }
}

最佳答案

我建议使用递归方法,而不是使用 while 循环。

function searchBST(rootNode, val) {
    if (rootNode.key === null)
        return null;

    var nodeKey = parseInt(rootNode.val);
    if (val < nodeKey) {
        return searchBST(rootNode.left, val);
    } else if (val > nodeKey) {
        return searchBST(rootNode.right, val);
    } else {
        return rootNode.value;
    }
}

此函数将返回具有搜索值的节点,如果您只想检查是否存在具有特定值的节点,只需使用 false 编辑返回值正确

关于javascript - 如何查找二叉树中是否存在值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37292620/

相关文章:

javascript - 使用 jQuery 我想在 TD 悬停时突出显示表中的列

java - 如何更改 servlet 中路径的主机和端口?

java - sessionFactory.openSession 中的 NullPointerException

java - 使用 jsp 和 servlet 上传多个文件

javascript - 动态改变html元素

javascript - 我可以使用 JavaScript 调整图像大小吗(不是缩放,实际调整大小)

javascript - iframe jquery 或 javascript 的刷新按钮

html - React中的图片标签

html - 图像输出 rom R 分辨率低

html - Twitter Bootstrap 在同一行的复选框和单选按钮