function findParentChildPairs(tree, bottomIds) {
const parentChildPairs = [];
function traverse(node, parentId) {
if (bottomIds.includes(node.id)) {
parentChildPairs.push({ pid: parentId, id: node.id });
}
node.children.forEach(child => traverse(child, node.id));
}
tree.forEach(node => traverse(node, ''));
return parentChildPairs;
}
// 示例树结构
const tree = [
{
id: '1',
value: 'Root',
children: [
{
id: '2',
value: 'Child 2',
children: [
{ id: '4', value: 'Child 4', children: [] },
{ id: '5', value: 'Child 5', children: [] }
]
},
{
id: '3',
value: 'Child 3',
children: [
{ id: '6', value: 'Child 6', children: [] },
{ id: '7', value: 'Child 7', children: [] }
]
}
]
}
];
// 已知的最底层节点 ID
const bottomIds = ['4', '6'];
// 获取父子节点组合
const parentChildPairs = findParentChildPairs(tree, bottomIds);
console.log(parentChildPairs); //[{pid: '2', id: '4'},{pid: '3', id: '6'}]
通过树的子节点,找到其父节点
最新推荐文章于 2024-05-31 18:07:42 发布