[英]DepthFirstInOrer in JS - test code fail to print the value
我已經創建了一個方法來優先遍歷深度,以便在我的二叉樹 class 中遞歸。
我不明白在哪里添加 this.value 以按預期在我的測試代碼中接收我的左孩子和右孩子的價值。 我已經嘗試了所有可能的地方但沒有成功。 當我使用 console.log 進行調試時,我只能設法獲取值或 [Function (anonymous)]
方法:
traverseDepthFirstInOrder(fn) {
//handle left child (if exists)
if (this.left) {
this.left.traverseDepthFirstInOrder(fn);
}
//handle right child (if exists)
if (this.right) {
this.right.traverseDepthFirstInOrder(fn);
}
}
測試代碼:
test("should call the fn on left nodes, center nodes, then right nodes", () => {
let test = [];
binaryTree.add(4);
binaryTree.add(14);
binaryTree.add(6);
binaryTree.add(16);
binaryTree.add(2);
binaryTree.add(12);
binaryTree.traverseDepthFirstInOrder(e => test.push(e.value));
expect(test).toEqual([2, 4, 6, 10, 12, 14, 16]);
});
終端失敗:
這就是 trincot 評論中的意思。 這應該以有序的方式遍歷樹,在每個節點上調用提供的inorder
。 但是您沒有撥打 function。您漏掉了一行:
class Tree { constructor (value, left = null, right = null) {this.value = value; this.left = left; this.right = right} traverseDepthFirstInOrder (fn) { //handle left child (if exists) if (this.left) { this.left.traverseDepthFirstInOrder(fn); } // handle the root node fn (this) // *** This line was missing *** //handle right child (if exists) if (this.right) { this.right.traverseDepthFirstInOrder(fn); } } } const binaryTree = new Tree (10, new Tree (4, new Tree (2), new Tree (6)), new Tree (14, new Tree (12), new Tree (16))) let test = []; binaryTree.traverseDepthFirstInOrder(e => test.push(e.value)); console.log (test)
忽略構造函數和我創建樹的方法; 我沒有您使用的 class 中的 rest。 但此更改也應該修復您的版本。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.