二叉树层序遍历
思路:
- 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;
}