misty0304 / day-interview

前端每日一题,提倡每日学习与思考,每天进步一点!
13 stars 1 forks source link

【js】说说深度优先遍历与广度优先遍历 #76

Open misty0304 opened 4 years ago

misty0304 commented 4 years ago

深度优先遍历(DFS),使用的是递归方法,比较通用。

广度优先遍历(BFS)是先遍历第一层,然后遍历第二层,层层遍历的方式。

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)
      for (let i = 0; i < children.length; i++) {
        stack.push(children[i])
      }
    }
  }
  return nodes
}