切换主题
图的遍历 
时间复杂度:O(n);空间复杂度:O(n)。
深度优先遍历 
模拟后进(Array#push) 先出(Array#pop)的栈数据结构。
JavaScript
const dfs = (node, ret = []) => {
  if (!node) return ret
  // 使用 set 标记已遍历过的节点
  const [stack, set] = [[node], new Set([node])]
  ret.push(node.val)
  while (stack.length) {
    const curr = stack.pop()
    for (const next of curr.nexts) {
      // 把 curr 重新压回栈
      stack.push(curr, next)
      set.add(next)
      ret.push(next.val)
      break
    }
  }
  return ret
}宽度优先遍历 
模拟先进(Array#push) 先出(Array#shift)的队列数据结构。
JavaScript
const bfs = (node, ret = []) => {
  if (!node) return ret
  // 使用 set 标记已遍历过的节点
  const [queue, set] = [[node], new Set([node])]
  while (queue.length) {
    // ==>节点出队时即为操作时间点
    const curr = queue.shift()
    // <==
    ret.push(curr.val)
    for (const next of curr.nexts) {
      if (!set.has(next)) {
        queue.push(next)
        set.add(next)
      }
    }
  }
  return ret
}数据结构应用 
leetcode
暂无