[英]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>');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.