前端知识点复习-深度优先和广度优先算法

深度优先:从树节点的最左边第一个子节点开始遍历,如果当前节点还有子节点则继续往下遍历,无子节点则往右跳到下一个兄弟节点遍历:

function dfs(node, nodeList = []) {
  nodeList.push(node);
  children = node.children;
  for(let i = 0; i < children.length; i++) {
    dfs(children[i], nodeList)
  }
  return nodeList
}

广度优先:从树的根节点开始,按照从左往右的顺序遍历其子节点,当前层次无兄弟节点后,从第一个节点的子节点开始继续遍历:

function bfs(node) {
  var nodes = [];
  if (node) {
    var queue = [node];
    while(queue.length) {
      var item = queue.shift();
      nodes.push(item);
      for(let i = 0;i < item.children.len;i++) {
        queue.push(item.children[i]);
      }
    }
  }
  return nodes;
}
posted @ 2021-03-01 15:49  lsboom  阅读(334)  评论(0)    收藏  举报