题目
给定一个不完全树结构 <不含有根节点的树结构> ,修改指定id的节点值(蚂蚁二面的一个编程题)。和我的另外一篇博客是姊妹篇,这个题目需要借助那篇文章实现的函数完成。其实就是将不完全树结构下面的每一个独立的元素集合作为一个完全树结构来检索就好了。
代码
// 需求:给定一个不完全树结构 <不含根节点> ,修改指定id的节点值(蚂蚁二面的一个编程题)
// 数据源
const treeData = [{
id: '1-1',
title: '层级1-1',
children: [{
id: '1-1-1',
title: '层级1-1-1',
}, {
id: '1-1-2',
title: '层级1-1-2',
}, {
id: '1-1-3',
title: '层级1-1-3',
}, {
id: '1-1-4',
title: '层级1-1-4',
}]
}, {
id: '1-2',
title: '层级1-2',
children: [{
id: '1-2-1',
title: '层级1-2-1',
}, {
id: '1-2-2',
title: '层级1-2-2',
}, {
id: '1-2-3',
title: '层级1-2-3',
}, {
id: '1-2-4',
title: '层级1-2-4',
}]
}, {
id: '1-3',
title: '层级1-3',
children: [{
id: '1-3-1',
title: '层级1-3-1',
}, {
id: '1-3-2',
title: '层级1-3-2',
}, {
id: '1-3-3',
title: '层级1-3-3',
}, {
id: '1-3-4',
title: '层级1-3-4',
}]
}]
// 深拷贝函数
const _clone = data => {
if (!data || !(data instanceof Object) || (typeof data == "function")) {
return data || undefined;
}
let constructor = data.constructor;
let result = new constructor();
for (var key in data) {
if (data.hasOwnProperty(key)) {
result[key] = _clone(data[key]);
}
}
return result;
}
const changeTreePostionData = (tree, id, changeTitle) => {
const searchId = (source, id) => {
for (let i = 0; i < source.length; i++) {
const item = source[i]
if (item.id === id) {
item.title = changeTitle
return
}
if (item.children) { // 只对非末端节点进行递归
searchId(item.children, id)
}
}
}
for (let i = 0; i < tree.length; i++) {
const item = tree[i];
// 将每个单独的数组元素视为一个完整树结构
// 根节点判定
if (item.id === id) {
item.title = changeTitle
return tree
}
if(item.children){
searchId(item.children, id)
}
}
return tree
}
// 测试数据准备
const deepCloneData = treeData.map(item => _clone(item))
const testId = '1-2-3'
const testChangeValue = '不完全树结构'
const resultData = changeTreePostionData(deepCloneData, testId, testChangeValue)
console.log('原始数据-->', treeData)
console.log('修改数据-->', resultData)
代码结果

补充
这是面试题的原数据,带入上面的函数,测试通过。
[
{
title: '0-0',
id: '0-0',
children: [
{
title: '0-0-0',
id: '0-0-0',
children: [
{ title: '0-0-0-0', id: '0-0-0-0' },
{ title: '0-0-0-1', id: '0-0-0-1' },
{ title: '0-0-0-2', id: '0-0-0-2' },
],
},
{
title: '0-0-1',
id: '0-0-1',
children: [
{ title: '0-0-1-0', id: '0-0-1-0' },
{ title: '0-0-1-1', id: '0-0-1-1' },
{ title: '0-0-1-2', id: '0-0-1-2' },
],
},
{
title: '0-0-2',
id: '0-0-2',
},
],
},
{
title: '0-1',
id: '0-1',
children: [
{ title: '0-1-0-0', id: '0-1-0-0' },
{ title: '0-1-0-1', id: '0-1-0-1' },
{ title: '0-1-0-2', id: '0-1-0-2' },
],
},
{
title: '0-2',
id: '0-2',
},
]

901

被折叠的 条评论
为什么被折叠?



