深度优先遍历和广度优先遍历

Posted bigman-bugman

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了深度优先遍历和广度优先遍历相关的知识,希望对你有一定的参考价值。

深度优先遍历(Depth First Search)

自顶点起, 往下一个邻近点走,一直走,走不动了,退回一部。这样反复;

/*深度优先遍历三种方式*/
let deepTraversal1 = (node, nodeList = []) => {
  if (node !== null) {
    nodeList.push(node)
    let children = node.children
    for (let i = 0; i < children.length; i++) {
      deepTraversal1(children[i], nodeList)
    }
  }
  return nodeList
}
let deepTraversal2 = (node) => {
    let nodes = []
    if (node !== null) {
      nodes.push(node)
      let children = node.children
      for (let i = 0; i < children.length; i++) {
        nodes = nodes.concat(deepTraversal2(children[i]))
      }
    }
    return nodes
  }
// 非递归
let deepTraversal3 = (node) => {
  let stack = []
  let nodes = []
  if (node) {
    // 推入当前处理的node
    stack.push(node)
    while (stack.length) {
      let item = stack.pop()
      let children = item.children
      nodes.push(item)
      // node = [] stack = [parent]
      // node = [parent] stack = [child3,child2,child1]
      // node = [parent, child1] stack = [child3,child2,child1-2,child1-1]
      // node = [parent, child1-1] stack = [child3,child2,child1-2]
      for (let i = children.length - 1; i >= 0; i--) {
        stack.push(children[i])
      }
    }
  }
  return nodes
}

 倒序插入栈结构数据中   3 2 1,取出1, 然后放入 6 5 4,反复;

广度优先遍历(Breadth First Search)

自顶点起,往所有的邻近点走,走完一圈之后,再走第二圈。这样反复;

let widthTraversal2 = (node) => {
  let nodes = []
  let stack = []
  if (node) {
    stack.push(node)
    while (stack.length) {
      let item = stack.shift()
      let children = item.children
      nodes.push(item)
        // 队列,先进先出
        // nodes = [] stack = [parent]
        // nodes = [parent] stack = [child1,child2,child3]
        // nodes = [parent, child1] stack = [child2,child3,child1-1,child1-2]
        // nodes = [parent,child1,child2]
      for (let i = 0; i < children.length; i++) {
        stack.push(children[i])
      }
    }
  }
  return nodes
}

  队列结构,正序插入,1 2 3,取出1, 然后插入 4 5 6,反复

以上是关于深度优先遍历和广度优先遍历的主要内容,如果未能解决你的问题,请参考以下文章

数据结构—深度优先遍历广度优先遍历图遍历算法的应用

数据结构C语言版 图的广度优先遍历和深度优先遍历 急急急 会查重

图的深度优先遍历DFS和广度优先遍历BFS(邻接矩阵存储)超详细完整代码进阶版

图的深度/广度优先遍历C语言程序

广度优先遍历和深度优先遍历的真正区别

数据结构 深度优先遍历