JavaScript Depth-first search

前端 未结 1 1719
深忆病人
深忆病人 2021-01-01 03:15

I am trying to implement DFS in JavaScript but I am having a little problem. Here is my Algorithm class:

\"use strict\";

define([], function () {

    retur         


        
相关标签:
1条回答
  • 2021-01-01 03:33

    The problem is your addChild() method only expects one parameter, but you are passing in multiple nodes to it.

    Change your calling code to:

    node1.addChild(node2);
    node1.addChild(node7);
    node1.addChild(node8);
    
    node2.addChild(node3);
    node2.addChild(node6);
    
    node3.addChild(node4);
    node3.addChild(node5);
    
    node8.addChild(node9);
    node8.addChild(node12);
    
    node9.addChild(node10);
    node9.addChild(node11);
    

    Or you can change addChild to accept multiple children (probably want to change the name too):

    this.addChildren = function () {
        for (var i = 0; i < arguments.length; i++) {
            children.push(arguments[i]);
        }
    };
    
    0 讨论(0)
提交回复
热议问题