function findCommonParentId(root,ids){
// 判断子节点是否在这个树上
function hasNode(root,id){
if(root.id == id){
return true
}else{
const children = root.children
if(children && children.length){
for(let i = 0; i < children.length ; i++){
if(hasNode(children[i],id)){
return true
}
}
}
}
}
function curNodehasAll(root,ids){
let falseLength = 0
let trueLength = 0
for(let i = 0 ; i < ids.length; i++){
if(!hasNode(root,ids[i])){
falseLength++
}else{
trueLength++
}
}
if(trueLength==ids.length) return 2 //全部在这个树上
if(falseLength == ids.length) return 0 //全部不在这个树上
return 1 //有一部分在这个树上
}
function dfs(root,ids,parentId){
const type = curNodehasAll(root,ids)
if( type == 1){
return parentId
}else if(type == 2){
const children = root.children
if(children && children.length){
for(let i = 0; i < children.length ; i++){
const rst = dfs(children[i],ids,root.id)
if(rst){
return rst
}
}
}
}
}
return dfs(root,ids,null)
}
找多个子节点最近父级的id
最新推荐文章于 2024-07-14 18:15:43 发布