实现

借助队列实现

function Tree(num) {
  this.num = num
  this.subs = []
}
Tree.prototype.add = function (item) {
  this.subs.push(item)
}
function orderTree(t0, cb) {
  let arr = []
  arr.push(t0)
  while (arr.length !== 0) {
    let p = arr.shift()
    cb(p.num)
    if (p.subs.length > 0) {
      p.subs.forEach((s) => {
        arr.push(s)
      })
    }
  }
}
// no-log

测试

// log
let t0 = new Tree(0)
let t1 = new Tree(1)
let t2 = new Tree(2)
let t3 = new Tree(3)
let t4 = new Tree(4)
let t5 = new Tree(5)
let t6 = new Tree(6)
let t7 = new Tree(7)
let t8 = new Tree(8)
let t9 = new Tree(9)
/*
0
|-----|------|
1     2      3
|||   |||    
456   789    
*/
t0.add(t1)
t0.add(t2)
t0.add(t3)
t1.add(t4)
t1.add(t5)
t1.add(t6)
t2.add(t7)
t2.add(t8)
t2.add(t9)

orderTree(t0, (i) => console.log(i))