js实现树形结构
实现树形结构的方法
在JavaScript中实现树形结构通常涉及创建节点对象,并通过递归或迭代方式构建层级关系。以下是几种常见方法:
使用对象和数组表示树
树的基本结构可由对象和数组组合实现,每个节点包含数据和子节点引用:

const tree = {
value: 'root',
children: [
{
value: 'child1',
children: [
{ value: 'grandchild1', children: [] },
{ value: 'grandchild2', children: [] }
]
},
{
value: 'child2',
children: []
}
]
};
类实现树节点
通过类定义树节点,便于扩展方法:
class TreeNode {
constructor(value) {
this.value = value;
this.children = [];
}
addChild(childNode) {
this.children.push(childNode);
}
}
const root = new TreeNode('root');
const child1 = new TreeNode('child1');
root.addChild(child1);
递归遍历树
深度优先遍历示例:

function traverse(node) {
console.log(node.value);
node.children.forEach(child => traverse(child));
}
traverse(tree);
扁平数组转树结构
将扁平数组转换为层级树:
function buildTree(items, parentId = null) {
return items
.filter(item => item.parentId === parentId)
.map(item => ({
...item,
children: buildTree(items, item.id)
}));
}
const flatArray = [
{ id: 1, parentId: null, name: 'root' },
{ id: 2, parentId: 1, name: 'child1' },
{ id: 3, parentId: 1, name: 'child2' }
];
const tree = buildTree(flatArray);
常用树操作
查找节点:
function findNode(root, targetValue) {
if (root.value === targetValue) return root;
for (const child of root.children) {
const found = findNode(child, targetValue);
if (found) return found;
}
return null;
}
这些方法覆盖了树形结构的基本实现和常见操作,可根据具体需求选择或组合使用。






