码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2020-02-07 22:23:41      阅读:68      评论:0      收藏:0      [点我收藏+]

标签:正序   traversal   stack   while   i++   children   一个   三种方式   turn   

深度优先遍历(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,反复

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

标签:正序   traversal   stack   while   i++   children   一个   三种方式   turn   

原文地址:https://www.cnblogs.com/bigman-bugman/p/12274769.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!