breadth-first traversal of a tree in javascript

前端 未结 1 989
情书的邮戳
情书的邮戳 2020-12-23 17:49

I am trying to learn data structures well and implemented the following code for a depth-first traversal/application of a callback on a regular tree:

Tree.pr         


        
相关标签:
1条回答
  • 2020-12-23 18:11

    Fundamentally, the difference between DFS and BFS is that with a DFS you push the children of the current node onto a stack, so they will be popped and processed before everything else, while for BFS you push the children onto the end of a queue, so they will be popped and processed after everything else.

    DFS is easy to implement recursively because you can use the call stack as the stack. You can't do that with BFS, because you need a queue. Just to make the similarity clear, lets convert your DFS to an iterative implementation first:

    //DFS
    Tree.prototype.traverse = function (callback) {
      var stack=[this];
      var n;
    
      while(stack.length>0) {
    
        n = stack.pop();
        callback(n.value);
    
        if (!n.children) {
          continue;
        }
    
        for (var i = n.children.length-1; i>=0; i--) {
           stack.push(n.children[i]);
        }
      }
    };
    

    And now BFS

    //BFS
    Tree.prototype.traverse = function (callback) {
      var queue=[this];
      var n;
    
      while(queue.length>0) {
    
        n = queue.shift();
        callback(n.value);
    
        if (!n.children) {
          continue;
        }
    
        for (var i = 0; i< n.children.length; i++) {
           queue.push(n.children[i]);
        }
      }
    };
    
    0 讨论(0)
提交回复
热议问题