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

给一个数据结构如下
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"},
        ]
    }
]

}
];

然后让封装一个函数, 根据名称得到其遍历的路径. 例如参数是 HUAWEI Mate 20. 那么函数返回 手机 / HUAWEI/HUAWEI Mate 20. 要求函数可以适用多层的数据结构, 例如上面的数据只有三层深度, 如果扩展为 10 层的话函数仍然可以适用.

这个题目的其实就是一个树的遍历, 然后返回这个遍历路径. 但是想了半天没想到如何写

阅读 3.1k
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))
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'))
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题