查找指定节点 children
findNodeInTreeByCode(tree, target) {
for (const node of tree) {
if (node.id === target) {
return node;
}
if (node.children && node.children.length > 0) {
const foundNode = this.findNodeInTreeByValue(node.children, target);
if (foundNode) {
return foundNode;
}
}
}
return null;
},
查找指定节点的所有叶子节点 children
findLeafNodes(tree, target) {
const targetNode = this.findNodeInTreeByValue(tree, target);
if (!targetNode) {
return null;
}
const leafNodes = [];
function traverse(node) {
if (!node.children || node.children.length === 0) {
leafNodes.push(node);
} else {
for (const child of node.children) {
traverse(child);
}
}
}
traverse(targetNode);
return leafNodes;
},
查找整棵树的所有叶子节点 children
findAllLeafNodes(tree) {
const leafNodes = [];
function traverse(node) {
if (!node.children || node.children.length === 0) {
leafNodes.push(node);
} else {
for (const child of node.children) {
traverse(child);
}
}
}
for (const node of tree) {
traverse(node);
}
return leafNodes;
},
获取指定节点的所有子孙节点 parentId
function getDescendants(nodes, id) {
const childNodes = nodes.filter((n) => n.parentId === id);
if (childNodes.length === 0) {
return [];
}
return childNodes.concat(
childNodes.map((node) => getDescendants(nodes, node.id)).flat(),
);
}
判断树形结构中的某个节点是否为叶子节点 parentId
function isTreeLeafNode(row, arr) {
if (!row.parentId) {
return false;
}
const res = arr.find((item) => item.parentId === row.id);
return !res;
}
查找指定节点的所有父节点 parentId
function findParentNodes(arr, targetId) {
const result = [];
arr.forEach((node) => {
if (node.id === targetId && node.parentId !== null) {
result.unshift(node.parentId);
result.unshift(...findParentNodes(arr, node.parentId));
}
});
return result;
}
查找树中的第一个叶子节点 children
function findFirstLeafNode(tree) {
function traverse(node) {
if (!node.children || node.children.length === 0) {
return node;
}
for (const child of node.children) {
const result = traverse(child);
if (result) {
return result;
}
}
}
for (const node of tree) {
const result = traverse(node);
if (result) {
return result;
}
}
return null;
}