js 实现tree
JavaScript 实现树结构
在 JavaScript 中实现树结构可以通过对象或类来完成。以下是几种常见的实现方式:
使用对象字面量
通过嵌套对象表示树的节点和子节点:

const tree = {
value: 'root',
children: [
{
value: 'child1',
children: [
{ value: 'grandchild1', children: [] },
{ value: 'grandchild2', children: [] }
]
},
{
value: 'child2',
children: []
}
]
};
使用类实现
定义一个 TreeNode 类来创建树节点:

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');
const child2 = new TreeNode('child2');
const grandchild1 = new TreeNode('grandchild1');
const grandchild2 = new TreeNode('grandchild2');
root.addChild(child1);
root.addChild(child2);
child1.addChild(grandchild1);
child1.addChild(grandchild2);
树的遍历方法
实现树的深度优先遍历(DFS)和广度优先遍历(BFS):
// 深度优先遍历
function dfs(node) {
console.log(node.value);
node.children.forEach(child => dfs(child));
}
// 广度优先遍历
function bfs(root) {
const queue = [root];
while (queue.length > 0) {
const node = queue.shift();
console.log(node.value);
node.children.forEach(child => queue.push(child));
}
}
实用场景示例
查找树中是否存在某个值:
function containsValue(node, target) {
if (node.value === target) return true;
for (const child of node.children) {
if (containsValue(child, target)) return true;
}
return false;
}
这些方法可以根据具体需求进行调整和扩展。






