首页 > Web开发 > 详细

js层序遍历多叉树

时间:2020-09-27 21:23:48      阅读:163      评论:0      收藏:0      [点我收藏+]

实现

借助队列实现

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))

js层序遍历多叉树

原文:https://www.cnblogs.com/oceans/p/13741228.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!