【发布时间】:2022-01-20 01:23:25
【问题描述】:
我已经尝试了很长时间,但似乎无法找到终止循环的方法。我不确定我是否走在正确的轨道上。我正在尝试进行广度优先(级别顺序)并在遍历时在每个节点上应用回调。
这里是构造函数和广度优先搜索的方法……
function BinarySearchTree(value) {
this.value = value;
this.right = null;
this.left = null;
}
BinarySearchTree.prototype.add = function(value) {
if (value < this.value) {
if (this.left) this.left.add(value);
else this.left = new BinarySearchTree(value);
}
if (value > this.value){
if (this.right) this.right.add(value);
else this.right = new BinarySearchTree(value);
}
};
BinarySearchTree.prototype.breadthFirst = function(callback) {
let queue = [];
queue.push(this.value);
while (queue.length) {
queue.pop();
callback(this.value);
if (this.left) queue.push(this.left);
if (this.right) queue.push(this.right);
}
};
关于我为什么会出现无限循环的任何想法?任何提示或帮助将不胜感激!
更新:示例数据...
var array = [];
var func = function(value){ array.push(value); };
binarySearchTree.add(2);
binarySearchTree.add(3);
binarySearchTree.add(7);
binarySearchTree.add(6);
console.log(binarySearchTree.breadthFirst(func)); -> should output [ 5, 2, 3, 7, 6 ]
这个我试过了……
BinarySearchTree.prototype.breadthFirst = function(callback) {
const queue = [];
let queueLength = this.value.length;
if (queueLength) {
queueLength--;
callback(this.value);
if (this.left) {
queue.push(this.left);
this.left.breadthFirst(callback);
}
if (this.right) {
queue.push(this.right);
this.right.breadthFirst(callback);
}
};
};
还有这个……
BinarySearchTree.prototype.breadthFirst = function(callback) {
const queue = [];
let queueLength = this.value.length;
while (queueLength) {
queueLength--;
callback(this.value);
if (this.left) {
queue.push(this.left);
callback(this.left);
}
if (this.left) {
queue.push(this.left);
callback(this.left);
}
};
};
以及其他变体,我仍然得到一个空数组作为输出!
【问题讨论】:
-
我认为您只想将
this.left和this.right推送到队列中(如果它们存在)。所以if (this.left) queue.push(this.left) -
忘了说我已经试过了...
-
您有数据样本吗?你的二叉树有没有可能有循环?
-
感谢您的提问...我用一些示例数据对其进行了更新。我有机会在那里有一个循环。这是我正在构建的第一棵二叉树!
标签: javascript binary-search-tree infinite-loop breadth-first-search