js 实现树形结构
实现树形结构的方法
在JavaScript中实现树形结构通常涉及创建节点对象、构建树以及遍历树。以下是几种常见的方法:
定义树节点结构
每个树节点包含数据和子节点引用,可以使用对象或类实现。
class TreeNode {
constructor(data) {
this.data = data;
this.children = [];
}
addChild(child) {
this.children.push(child);
}
}
构建树实例
通过实例化节点并添加子节点来构建树结构。
const root = new TreeNode('Root');
const child1 = new TreeNode('Child1');
const child2 = new TreeNode('Child2');
root.addChild(child1);
root.addChild(child2);
递归遍历树
深度优先遍历(DFS)是处理树形结构的常用方法,递归实现简洁直观。
function traverse(node) {
console.log(node.data);
node.children.forEach(child => traverse(child));
}
traverse(root);
广度优先遍历(BFS)
使用队列实现层级遍历,适合需要按层级处理的场景。
function bfsTraverse(root) {
const queue = [root];
while (queue.length > 0) {
const current = queue.shift();
console.log(current.data);
queue.push(...current.children);
}
}
bfsTraverse(root);
查找节点
通过遍历实现条件查找,递归或迭代均可。
function findNode(node, targetData) {
if (node.data === targetData) return node;
for (const child of node.children) {
const found = findNode(child, targetData);
if (found) return found;
}
return null;
}
删除节点
需要先找到目标节点的父节点,再从其子节点列表中移除。
function removeNode(root, targetData) {
if (root.data === targetData) return null;
root.children = root.children.filter(child => {
if (child.data === targetData) return false;
removeNode(child, targetData);
return true;
});
return root;
}
应用场景扩展
- 扁平数据转树形:通过ID和父ID关联构建树结构。
- 树形数据扁平化:通过遍历将树转换为数组形式。
- 动态加载子树:异步加载子节点数据优化性能。
根据具体需求选择合适的数据结构和算法,例如需要频繁查找时可考虑使用Map存储节点引用。







