class TreeNode {
constructor(id, parentId, name, children = []) {
this.id = id;
this.parentId = parentId;
this.name = name;
this.children = children;
}
// 添加子节点
addChildren(node) {
this.children.push(node);
}
// 删除子节点
deleteChildren(nodeId) {
this.children = this.children.filter(child => child.id !== nodeId);
}
}
class Tree {
constructor(rootNode) {
this.rootNode = rootNode;
}
// 构建树形结构
buildTree(nodes) {
let tree = [];
let map = {};
for (let i = 0; i < nodes.length; i++) {
let node = nodes[i];
map[node.id] = i;
if (node.parentId === null || node.parentId === undefined) {
tree.push(new TreeNode(node.id, null, node.name, this.buildChildren(nodes, node.id)));
} else {
nodes[map[node.parentId]].addChildren(new TreeNode(node.id, null, node.name, this.buildChildren(nodes, node.id)));
}
}
return new Tree(tree);
}
// 构建子节点
buildChildren(nodes, parentId) {
let children = [];
for (let i = 0; i < nodes.length; i++) {
if (nodes[i].parentId === parentId) {
children.push(new TreeNode(nodes[i].id, null, nodes[i].name, this.buildChildren(nodes, nodes[i].id)));
}
}
return children;
}
}