美文网首页
树的DFS与BFS

树的DFS与BFS

作者: 围观工程师 | 来源:发表于2018-06-22 01:25 被阅读0次

Data

let node = {
  txt: '1',
  children: [{
    txt: '11',
    children: [{
      txt: '111'
    }, {
      txt: '112'
    }, {
      txt: '113'
    }]
  }, {
    txt: '12',
    children: [{
      txt: '121'
    }, {
      txt: '122'
    }, {
      txt: '123'
    }]
  }, {
    txt: '13',
    children: [{
      txt: '131'
    }, {
      txt: '132'
    }, {
      txt: '133'
    }]
  }]
}

DFS

let stack = [node]

while (stack.length > 0) {
  let node = stack.shift()
  console.log(node.txt)
  if (node.children) {
    let children = node.children
    for (let i = children.length-1; i >= 0; i--) {
      stack.unshift(children[i])
    }
  }
}

BFS

let queue = [node]

while(queue.length > 0) {
  let obj = queue.shift()
  console.log(obj.txt)
  if (obj.children) obj.children.forEach(item => queue.push(item))
}

相关文章

网友评论

      本文标题:树的DFS与BFS

      本文链接:https://www.haomeiwen.com/subject/kryhyftx.html