如何查找值是否存在于二叉树中
how to find value is present in binary tree or not
请告诉我如何查找二进制树中是否存在值?我想找到值是存在于二叉树的左节点还是右节点?
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
和true
编辑返回值即可
如果在树中找到值,则可以离开函数。
function Node(value) {
this.value = value;
// this.left = null;
// this.right = null;
}
function BinarySearchTree() {
this._root = null;
}
BinarySearchTree.prototype = {
insert: function (value) {
var node = this,
side = '_root';
while (node[side]) {
node = node[side];
if (value === node.value) {
return;
}
side = value < node.value ? 'left' : 'right';
}
node[side] = new Node(value);
},
contains: function (value) {
var current = this._root
while (current) {
document.write('value: ' + current.value + '<br>');
if (value === current.value) {
return true; // leave the function
}
current = value < current.value ? current.left : current.right;
}
return false;
},
};
var tree = new BinarySearchTree(),
i;
for (i = 0; i < 10; i++) {
tree.insert(Math.floor(Math.random() * 1000));
}
document.write(tree.contains(42) + '<br>');
tree.insert(42);
document.write(tree.contains(42) + '<br>');
document.write('<pre>' + JSON.stringify(tree, 0, 4) + '</pre>');
相关文章:
- 用于检查数组中是否存在元素的javascript自定义方法
- 是否存在React Native“;WEB代码安全防护”;
- 验证会话中是否存在对象's数组
- 如何查找值是否存在于二叉树中
- 检查是否存在使用chrome扩展的javascript库
- 是否存在Javascript Liferay Service库的文档?如何处理错误情况
- 测试mongo脚本中是否存在参数
- 检查搜索结果是否存在多次如果是,则在Javascript中只显示一个结果
- 使用js/jQuery检查对象(而不是元素)是否真的存在
- 检查数组中是否存在字符串值,并返回找到的数组值js
- 如何通过json对象选项卡中的Id来检查对象是否存在
- 检查是否存在任意控制器/操作
- 如何检查一个字符串的所有字符是否都存在于另一个字符串中
- Javascript滑块不滑动,如何判断是否存在JS冲突
- 根据手机上是否存在文件,在jQuery mobile中动态填充列表视图
- javascript测试是否存在两个标志中的任何一个
- 如何使用javascript检查移动sd卡中是否存在文件
- 当提供函数名称时,检查函数是否存在于同一作用域中
- 需要帮助使用JQuery.inArray()检查值是否存在
- 在运行Javascript/jQuery中的函数之前,检查元素是否存在是否更具性能