zoukankan      html  css  js  c++  java
  • 深度优先遍历和广度优先遍历

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

  • 相关阅读:
    读者试读怎么评价这本书
    性能优化是数据库应用的核心问题
    ExtJS 4 Grid组件
    发挥你的SATA硬盘
    MOSS 修改了服务器账号密码后的问题
    速度真快,ExtJS第5个预览版发布
    Ext JS 4 Preview Release 4发布
    显卡性能排行榜
    手机操作系统发展史
    程序解读身份证的密码
  • 原文地址:https://www.cnblogs.com/bigman-bugman/p/12274769.html
Copyright © 2011-2022 走看看