var arr = [
{
name: "a",
children: [
{
name: "a1",
},
{ name: "a2" },
],
},
{
name: "b",
children: [
{
name: "b1",
children: [
{
name: "b11",
children: [
{
name: "b111",
},
{
name: "b12312",
},
],
},
],
},
],
},
];
期望:
[{
name: "a"
},{
name: "a1"
},{
name: "a2"
},{
name: "b"
},{
name: "b1"
},{
name: "b11"
},{
name: "b111"
}, {
name: "b12312"
}]
要求:
不适用递归
目前思考如下:(还没成功)
while + 栈
function each(tree) {
const result = [];
let index = 0;
let children = tree;
const stack = [];
while (children[index]) {
const child = children[index];
result.push(child);
if (Array.isArray(child.children)) {
stack.push({
children,
index,
});
children = child.children;
index = 0;
} else {
index++;
if (!children[index] && stack.length) {
const next = stack.pop();
children = next.children;
index = next.index + 1;
}
}
}
return result;
}
可行性答案 1
function each(tree) {
const result = [];
let index = 0;
let children = tree;
const stack = [];
stack.push({
children,
index,
});
while (children[index] || stack.length) {
const child = children[index];
if (child) {
result.push(child);
} else {
const next = stack.pop();
children = next.children;
index = next.index + 1;
continue;
}
if (Array.isArray(child.children)) {
stack.push({
children,
index: index,
});
children = child.children;
index = 0;
} else {
index++;
}
}
return result;
}