# 一道前端算法题, 想了要好久没想出来如何写 . 请指导一下

194 次浏览

var data = [
{

``````"name": "手机",
"childs": [
{
"name": "iPhone",
"childs": [
{"name": "iPhone X"},
{"name": "iPhone XR"},
{"name": "iPhone XS"},
]
},
{
"name": "HUAWEI",
"childs": [
{"name": "HUAWEI Mate 20"},
{"name": "HUAWEI Mate 20 X"},
{"name": "HUAWEI Mate 20 Pro"},
]
}
]``````

}
];

2019-05-21 提问
4 个回答

``````function f() {
var s = getPath("HUAWEI Mate 20 Pro", data[0], "");
console.log(s)
}

/**
*
* @param search  查询的子节点
* @param parent  根节点
* @param path    路径
* @returns {*}
*/
function getPath(search, parent, path) {
path = path + "/" + parent.name;
if (parent.name == search) return path;
if (parent.childs != null && parent.childs.length > 0) {
var childs = parent.childs;
for (var i = 0; i < childs.length; i++) {
var t = getPath(search, childs[i], path);
if (t == undefined || t == null || t == "") {
continue;
} else {
return t;
}
}
}
}``````
``````let path = [];
function getTree(data,extend) {
for (let z = 0; z < data.length; z++) {
const _data = data[z];
let extendarray = extend?JSON.parse(JSON.stringify(extend)):[];
if (_data.childs) {
extendarray.push(_data.name)
getTree(_data.childs,extendarray)
}else{
extendarray.push(_data.name)
path.push(extendarray)
}
}
}
getTree(data);
console.log(path);``````

``````const find = (target, childArr, curPath = '') => {
for (let i = 0; i < childArr.length; i += 1) {
const {name, childs} = childArr[i]
const path = `\${curPath}\${curPath ? '/' : ''}\${name}`
if (name === target) return path
if (childs) {
const rtn = find(target, childs, path)
if (rtn) return rtn
}
}
}

console.log(find('iPhone XR', data))``````
1

Ayden · 5月21日

``````function getNamePath(data, name) {
let namePath = ''

function _getNamePath(childs, parentNamePath) {
for (const child of childs) {
if (child.name === name) {
namePath = parentNamePath + '/' + name
} else {
const childs = child.childs
if (childs && childs.length > 0) {
let newParentNamePath = parentNamePath + '/' + child.name
_getNamePath(childs, newParentNamePath)
}
}
}
}
_getNamePath(data, '')
return namePath
}

console.log(getNamePath(data, 'HUAWEI Mate 20 Pro'))``````