javascript中广度优先遍历树

dev*_*r87 20 javascript tree data-structures

我正在努力学习数据结构并实现以下代码,以便在常规树上进行深度优先遍历/应用回调:

Tree.prototype.traverse = function (callback) {
  callback(this.value);

  if (!this.children) {
    return;
  }
  for (var i = 0; i < this.children.length; i++) {
    var child = this.children[i];
    child.traverse(callback);
  }
};
Run Code Online (Sandbox Code Playgroud)

我怎么能改变这一点,而不是先扩大它?这就是Tree Class的样子:

var Tree = function (value) {
  var newTree = {};

  newTree.value = value;
  newTree.children = [];
  extend(newTree, treeMethods);

  return newTree;
};
Run Code Online (Sandbox Code Playgroud)

Mat*_*ans 47

从根本上说,DFS和BFS之间的区别在于,使用DFS将当前节点的子节点推送到堆栈,因此它们将其他所有节点之前被弹出和处理,而对于BFS,您将子节点推送到队列的末尾,所以他们将其他一切之后被弹出和处理.

DFS很容易递归实现,因为您可以将调用堆栈用作堆栈.你不能用BFS做到这一点,因为你需要一个队列.为了使相似性清晰,我们首先将DFS转换为迭代实现:

//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]);
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

现在是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]);
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

  • 不,数组不像哈希表那样实现.您可以像散列一样使用它,但JS实现通常会优化数组以进行类似数组的访问.但是......它与上面没什么区别 - 分配一个新的哈希表也会同样地改变复杂性,而concat和push之间的区别在于concat分配一个全新的哈希表,而push则没有. (8认同)
  • @AndrasSzell 会将算法的复杂性从 O( |V| + |E| ) 更改为 O( |V|^2 + |E| ),因为 concat() 分配一个新数组。 (3认同)