
通过递归实现 js 中的 walk 函数
对于面试中的这份题目,我们需要使用 javascript 中的递归来实现一个名为 walk 的函数。该函数旨在将树形结构数据转换为列表数据。
实现方法:
1. 定义 walk 函数:
立即学习“Java免费学习笔记(深入)”;
function walk(list) {
// 递归函数代码
}2. 递归遍历树形结构:
在函数中,使用递归遍历树形结构,逐层深入。
3. 在递归过程中修改数据:
如果 encountering 遇到了具有 children 属性的节点,则:
- 分别对 children 递归调用 walk 函数,删除 children 属性。
- 将节点自身 push 到 output 数组中。
示例代码:
function walk(list) {
var output = [];
list.foreach(function(item) {
if (item.children) {
walk(item.children);
delete item.children;
}
output.push(item);
})
return output;
}样例输入和输出:
输入:
[{
id: 1,
text: 'text1',
children: [{
id: 2,
text: 'text2',
parentid: 1,
children: [{
id: 4,
text: 'text4',
parentid: 2
}]
}, {
id: 3,
text: 'text3',
parentid: 1
}]
}]输出:
[{
id: 4,
text: 'text4',
parentId: 2
}, {
id: 2,
text: 'text2',
parentId: 1
}, {
id: 3,
text: 'text3',
parentId: 1
}, {
id: 1,
text: 'text1'
}, ]










