基于对象数据是引用传递的特点,以及队列层序遍历的方式,利用队列的先进先出的来对每一个对象添加一个data属性
let nums = [
{
children: [{
children: []
},
{
children: []
},
{
children: []
}
]
},
{
children: [{
children: []
}]
}
]
let temp = nums.slice()
while (temp.length) {
const t = temp.shift()
t.data = 1
if (t.children.length) {
temp = temp.concat(t.children)
}
}
console.log(nums);
而栈的方式,比如查找一个节点的父节点
const tree = [{
data: 1,
child: [{
data: 2,
child: [{ data: 4 }],
},
{
data: 3,
child: [],
},
],
},
{
data: 7,
child: [{
data: 2,
child: [{ data: 4 }],
},
{
data: 3,
child: [],
},
],
}];
function find(treeList, data) {
let stackFindList = [].concat(treeList);
const stackParentList = treeList.map(() => treeList);
//同时建了一个父级栈在元素 入栈的同时 他的父级也入栈 两个栈是一一对应的关系
for (let i = 0; i < stackFindList.length; i++) {
const e = stackFindList[i];
if (e.data === data) {
return stackParentList[i];
}
if (e.child) {
stackFindList = stackFindList.concat(e.child);
e.child.forEach(() => {
stackParentList.push(e);
});
}
}
}