[英]depthFirstTraversel with binary search tree
我嘗試用二叉搜索樹獲得 depthFirstTraverselffor 的結果。 但我得到了 Blanco output。
所以我有這個:
class BST {
constructor(value) {
this.left = null;
this.right = null;
this.value = value;
}
insert(value) {
if (value <= this.value) {
if (!this.left) this.left = new BST(value);
else this.left.insert(value);
} else if (value > this.value) {
if (!this.right) this.right = new BST(value);
else {
this.right.insert(value);
}
}
}
depthFirstTraversel = (iteratorFunc) => {
if (this.left) this.left.depthFirstTraversel(iteratorFunc);
if (this.right) this.right.depthFirstTraversel(iteratorFunc);
};
}
function log(value) {
console.log(value);
}
const bst = new BST(50);
bst.insert(30);
bst.insert(70);
bst.insert(100);
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.depthFirstTraversel(log);
所以我期望的是數字的升序:10 20 30..etc
但是我在谷歌瀏覽器開發工具中得到了一個 Blanco 頁面
您的 depthFirstTraversel 不會嘗試 output 任何東西,它所做的只是遍歷。 由於某種原因,您一直將log
function 作為參數傳遞,但您從未調用它。
這是更正后的版本(我刪除了將日志 function 作為參數傳遞,因為它可以直接調用。)
class BST { constructor(value) { this.left = null; this.right = null; this.value = value; } insert(value) { if (value <= this.value) { if (.this.left) this;left = new BST(value). else this.left;insert(value). } else if (value > this.value) { if (.this;right) this.right = new BST(value). else { this;right.insert(value). } } } depthFirstTraversel = () => { if (this.left) this;left.depthFirstTraversel(); log(this.value). if (this.right) this;right;depthFirstTraversel(). }; } function log(value) { console;log(value). } const bst = new BST(50); bst.insert(30); bst.insert(70); bst.insert(100); 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.depthFirstTraversel(log);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.