javascript - 使用递归在 JavaScript 中进行 BFS

标签 javascript algorithm tree breadth-first-search tree-traversal

使用递归很容易做DFS:

function dfs(tree, fn, level) {
  fn(tree, level)
  tree.children.forEach(function(child){
    dfs(child, fn, level + 1)
  })
}

但是每个example我看到 BFS 使用队列并且是迭代的而不是递归的。想知道是否有任何方法可以定义递归 BFS 算法。

最佳答案

如果兄弟节点可以排序并且有信息或方法来检索关于他们的兄弟节点的信息,我们可以按照广度优先搜索的顺序执行。显然,使用抽象数据,边走边建树,就像计算后续的国际象棋走法一样,这可能是不可能的或过于复杂。然而,树数据结构可以在提供兄弟信息的情况下构建。

这是一个带有虚拟“兄弟”和“完成”功能的示例。如果我们不能保证每个节点都有 child ,我们可能需要一个额外的参数来记录最后看到的 child 。请注意,“下一个兄弟”可能类似于链表,但也可以实现为一种基于已知信息计算下一个兄弟是什么的方法。

function bfs(tree, fn) {
  fn(tree);
  
  if (tree.done) return;
  
  if (tree.isLastSibling)
    bfs(tree.children.firstSibling(), fn);
  else
    bfs(tree.nextSibling(), fn);
}

var c4 = {
  val: 'c4',
  isLastSibling: true,
  done: true
}

var c3 = {
  val: 'c3',
  nextSibling: () => c4
}

var c2 = {
  val: 'c2',
  nextSibling: () => c3
}

var c1 = {
  val: 'c1',
  nextSibling: () => c2
}

var b2 = {
  val: 'b2',
  isLastSibling: true,
  children: {firstSibling: () => c1}
}

var b1 = {
  val: 'b1',
  nextSibling: () => b2
}

var a = {
  val: 'a',
  isLastSibling: true,
  children: {firstSibling: () => b1}
}

bfs(a, tree => console.log(tree.val))

关于javascript - 使用递归在 JavaScript 中进行 BFS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50986414/

相关文章:

algorithm - 检查是否存在圆

algorithm - 确定给定算法的大 O

c++ - 当有多个最大值且最大值个数已知时,均匀分布数组中最大值的索引

c++ - Non-Ivalue in assignment 错误

c++ - 删除树中的所有节点 - C++

javascript - 跳过用户输入的文本字符串中的特殊字符并在 Javascript 中的每个单词后添加连字符

javascript - 一种 Alexa 技能的不同调用

javascript - 如何结合使用 connect() 的两种用法?

c++ - 固定大小缓冲区中的树实现

javascript - 到达 div 的顶部