(一) 創(chuàng)建一個 Node 類,生成樹的結點茧痕。
export default class Node {
name = '';
constructor(name) {
this.name = name;
}
children = [];
add(children) {
for (let i = 0; i < children.length; i += 1) {
const child = children[i];
if (child === null) {
return this;
}
if (child.parent != null) {
children[i].parent.remove(child);
}
child.parent = this;
this.children.push(child);
}
return null;
}
remove(child) {
const index = this.children.indexOf(child);
if (index > -1) {
child.parent = undefined;
this.children.slice(index, 1);
return child;
}
return null;
}
}
(二) 根據測試數據财岔,遞歸生成多叉樹。
const testNode = {
n0: {
children: ['n1', 'n2', 'n5'],
},
n1: {
children: ['n3', 'n8', 'n7'],
},
n2: {
children: [],
meshes: ['m1'],
},
n3: {
children: ['n4'],
},
n4: {
children: [],
meshes: ['m0'],
},
n5: {
children: [],
meshes: ['m1'],
},
n6: {
children: [],
},
n7: {
children: ['n10'],
},
n8: {
children: [],
meshes: ['m2'],
},
n9: {
children: [],
meshes: ['m3'],
},
n10: {
children: [],
meshes: ['m4'],
},
};
/**
* meshes 測試數據
*/
const meshesObj = {
children: [
{
aa: 'bb',
},
{
aa: 'bb',
},
{
aa: 'bb',
},
{
aa: 'bb',
},
{
aa: 'bb',
},
{
aa: 'bb',
},
],
};
/**
* 遞歸遍歷生成多叉樹
*
* @param {*} node - nodes 列表中的一個 node
* @param {*} parentNode - node 的父結點盏浇,為 Node 對象。
*/
const traverseNodes = (node, parentNode) => {
if (node.children.length > 0) {
const { length } = node.children;
for (let i = 0; i < length; i += 1) {
const nodeName = node.children[i];
const childNode = new Node(nodeName);
parentNode.add([childNode]);
const newChildren = testNode[nodeName];
traverseNodes(newChildren, childNode);
}
} else {
const { meshes } = node;
const meshesLsit = [];
for (let i = 0; i < meshes.length; i += 1) {
const meshName = meshes[i];
for (let j = 0; j < meshesObj.children.length; j += 1) {
const mesh = meshesObj.children[j];
if (mesh.name === meshName) {
meshesLsit.push(mesh);
}
}
}
parentNode.add(meshesLsit);
}
};
// 多叉樹的根結點
const root = new Node('n0');
traverseNodes(testNode.n0, root);
console.log(root);