如何实现DFS和BFS?

  • DFS(深度优先搜索):遍历当前节点的全部子节点。再遍历同一级的节点
  • BFS(广度优先搜索):遍历兄弟节点,再遍历节点下的子节点

测试dom:

    
123 sdsd 456

这是一个p标签

DFS递归实现:

    function deepTraversal(node, nodeList) {
      if (node) {
        nodeList.push(node)
        var children = node.children
        for (var i = 0; i < children.length; i++) {
          deepTraversal(children[i], nodeList)
        }
      }
      return nodeList
    }
    var root = document.getElementById('root')
    console.log(deepTraversal(root, nodeList = []))

DFS非递归实现:

   // DFS非递归实现
    function deepTraversal(node) {
      var nodeList = []
      if (node) {
        var stack = []
        stack.push(node)
        while (stack.length != 0) {
          var childrenItem = stack.pop()
          nodeList.push(childrenItem)
          var childrenList = childrenItem.children
          for (var i = childrenList.length - 1; i >= 0; i--) {
            stack.push(childrenList[i])
          }
        }
      }
      return nodeList
    }
    var root = document.getElementById('root')
    console.log(deepTraversal(root, nodeList = []))

 

如何实现DFS和BFS?_第1张图片

BFS实现:

    function wideTraversal(node) {
      var nodes = []
      if (node != null) {
        var queue = []
        queue.unshift(node)
        while (queue.length != 0) {
          var item = queue.shift()
          nodes.push(item)
          var children = item.children
          for (var i = 0; i < children.length; i++) {
            queue.push(children[i])
          }
        }
      }
      return nodes
    }
    var root = document.getElementById('root')
    console.log(wideTraversal(root))

如何实现DFS和BFS?_第2张图片 

 

参考:https://www.jianshu.com/p/b4d8085e84bd

你可能感兴趣的:(javascript)