树状结构转数组&二叉树层序遍历

二叉树层序遍历

思路:

  • queue 用于记录节点。根节点入队,出队。左/右子节点入队,出队
  • res 用于记录结果
function bfs(root){
  if(!root) return [];
  let queue = [];// 利用队列
  let res = [];
  queue.push(root);// 节点入队
  while(queue.length!=0){
    let node = queue.shift();// 弹出队首节点(出队)
    res.push(node.val);
    if(node.left){
      queue.push(node.left);// 左子节点入队
    }
    if(node.right){
      queue.push(node.right);// 右子节点入队
    }
    return res;
  }
}

当然,队列的特点是先进先出。我们也可以利用 stack 先进后出的特点,相应地改为 let node = queue.pop(); 出栈即可。

树状结构转数组

  • 树状结构:
let tree = 
[
  {
    id:0,
    name:'xxx',
    children:{
      id:1,name:'xxx',children:{},
      id:2,name:'xxx',children:{
        id:3,name:'xxx',children:{}
      }
    }
  }
]
  • 扁平数组结构
let list = 
[
  {id:0,name:'xxx',pid:null},
  {id:1,name:'xxx',pid:0},
  {id:2,name:'xxx',pid:0},
  {id:3,name:'xxx',pid:2},
]

实现:广度优先遍历

function treeToList(tree){
  let queue = [];
  let res = [];
  queue.concat(tree);// [{},{},...] 用 concat 而不是 push
  while(queue.length!=0){
    let obj = queue.shift();// 弹出队首元素
    if(obj.children){
      queue = queue.concat(obj.children);// 子节点入队
      delete obj["children"];// 删除 children 属性
    }
    res.push(obj);
  }
  return res;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值