-
Notifications
You must be signed in to change notification settings - Fork 15
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
阿里巴巴:将输入的数组组装成一颗树状的数据结构(一面) #4
Comments
梳理下我的解题思路: 那么针对上面的思路: 针对异常: function getTreeData(arr) {
if (!arr || !(arr instanceof Array)) return '错误的数据类型'
if (!arr.length) return '空数组'
var len = arr.length
var rootObj = {id: null, name: null, children: []}
var nodeObj = {}
for (var i = 0;i < len; i++) {
if (!arr[i].parentId) {
rootObj = {
id: arr[i].id,
name: arr[i].name,
children: [],
}
} else {
if (nodeObj.hasOwnProperty(arr[i].parentId)) {
nodeObj[arr[i].parentId].children.push(arr[i])
} else {
nodeObj[arr[i].parentId] = {}
nodeObj[arr[i].parentId].children = []
nodeObj[arr[i].parentId].children.push(arr[i])
}
}
}
// 整理根节点过程
function getChildren(node) {
if(nodeObj[node.id] && nodeObj[node.id].children){
node.children = nodeObj[node.id].children
delete(nodeObj[node.id])
var len = node.children.length
if (len > 0) {
for (var i = 0; i < len; i++) {
getChildren(node.children[i])
}
}
} else if(!nodeObj[node.id]){
console.log(node.id + '没有children')
}
}
getChildren(rootObj)
for(var p in nodeObj){
if(nodeObj.hasOwnProperty){
console.warn(p + ':没有该父节点')
}
}
return rootObj
} |
|
function toTree (data) { // 将数据存储为 以 id 为 KEY 的 map 索引数据列 |
To:
robinson90
面试公司:
阿里
面试环节:
一面
问题:
将输入的数组组装成一颗树状的数据结构 要求程序具有侦测错误输入的能力,假如数据是下面的,
The text was updated successfully, but these errors were encountered: