深度遍历-广度遍历

157 阅读1分钟

广度遍历

  • 广泛的遍历-依次遍历children每一个节点-但是不深入某一个节点
  • 遍历同一层级的每一个节点-再继续往下遍历

代码

var arr = [  {    id:1,    name:'1虹',    children: [      {id:2,name:'2虹',      children:[        {id:21,name:'21虹'},        {id:22,name:'22虹'},      ]},
      {id:3,name:'3虹',
      children:[
        {id:31,name:'31虹'},
        {id:32,name:'32虹'},
      ]}
    ]
  }
]

function node(data) {
  console.log(data,'data-obj')
}
function sort(arr) {
  var stack = []
  stack.push(arr[0])
  while(stack.length) {
    const data = stack.pop()
    node(data)
    const children = data.children
    if(children?.length) {
      children.forEach(item => {
        stack.unshift(item)
      })
    }
  }
}
sort(arr)

解析

  • 先进先出原则
  • 成立一个stack堆栈对原有数组不断进行 pop取出
  • 然后 stack不断unshift 添加道头部
  • 内部判断children?.length进行循环添加

image.png

深度遍历

  • 说白了就是深度-每次遍历先对里面的一个children进行遍历完成
  • 在去遍历临近的一个children的内容 依次类推
function sort(arr) {
  var stack = []
  stack.push(arr[0])
  while(stack.length) {
    const data = stack.pop()
    node(data)
    const children = data.children
    if(children?.length) {
      children.reverse().forEach(item => {
        stack.push(item)
      })
    }
  }
}

解析

  • 先进后出原则
  • 使用pop和push进行组合
  • 其次为了顺序正常使用reverse进行数组反转