简体   繁体   English

JS 中的 DepthFirstInOrer - 测试代码无法打印值

[英]DepthFirstInOrer in JS - test code fail to print the value

I've created a method to traverse Depth first in order with a recursion in my BinaryTree class.我已经创建了一个方法来优先遍历深度,以便在我的二叉树 class 中递归。

I don't understand where to add this.value for the value of my left child and right child to be received in my test code as expected.我不明白在哪里添加 this.value 以按预期在我的测试代码中接收我的左孩子和右孩子的价值。 I've tried every possible place but without success.我已经尝试了所有可能的地方但没有成功。 when I use console.log to debug, i can only manage to get the value or [Function (anonymous)]当我使用 console.log 进行调试时,我只能设法获取值或 [Function (anonymous)]

Method:方法:

      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);
    }
  }

testCode:测试代码:

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]);
    });

terminal failed:终端失败:

  • Expected - 9预期 - 9
    • Received + 1收到 + 1

This was what was meant in trincot's comment.这就是 trincot 评论中的意思。 This is supposed to traverse the tree in an inorder manner, calling the supplied function on every node.这应该以有序的方式遍历树,在每个节点上调用提供的inorder But you don't call the function. You're missing one line:但是您没有拨打 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)

Ignore the constructor and my method of creating the tree;忽略构造函数和我创建树的方法; I don't have the rest of the class you're using.我没有您使用的 class 中的 rest。 But this change should fix your version as well.但此更改也应该修复您的版本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM