js层序遍历多叉树

实现

借助队列实现

function Treenum) {
  this.num = num
  this.subs = []
}
Tree.prototype.add = function item) {
  this.subs.pushitem)
}
function orderTreet0, cb) {
  let arr = []
  arr.pusht0)
  while arr.length !== 0) {
    let p = arr.shift)
    cbp.num)
    if p.subs.length > 0) {
      p.subs.forEachs) => {
        arr.pushs)
      })
    }
  }
}
// no-log

测试

// log
let t0 = new Tree0)
let t1 = new Tree1)
let t2 = new Tree2)
let t3 = new Tree3)
let t4 = new Tree4)
let t5 = new Tree5)
let t6 = new Tree6)
let t7 = new Tree7)
let t8 = new Tree8)
let t9 = new Tree9)
/*
0
|-----|------|
1     2      3
|||   |||    
456   789    
*/
t0.addt1)
t0.addt2)
t0.addt3)
t1.addt4)
t1.addt5)
t1.addt6)
t2.addt7)
t2.addt8)
t2.addt9)

orderTreet0, i) => console.logi))

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注