当前位置:首页 > JavaScript

js实现树形结构

2026-03-01 02:36:59JavaScript

使用对象和数组构建树形结构

在JavaScript中,树形结构通常通过对象和数组的组合来实现。每个节点是一个对象,包含数据和子节点的引用。

const tree = {
  value: 'Root',
  children: [
    {
      value: 'Child 1',
      children: [
        { value: 'Grandchild 1', children: [] },
        { value: 'Grandchild 2', children: [] }
      ]
    },
    {
      value: 'Child 2',
      children: [
        { value: 'Grandchild 3', children: [] }
      ]
    }
  ]
};

递归遍历树结构

深度优先遍历(DFS)是处理树形结构的常见方法,递归是实现DFS的简洁方式。

function traverse(node) {
  console.log(node.value);
  node.children.forEach(child => {
    traverse(child);
  });
}

traverse(tree);

使用类实现树节点

通过类可以更规范地定义树节点,便于扩展和维护。

js实现树形结构

class TreeNode {
  constructor(value) {
    this.value = value;
    this.children = [];
  }

  addChild(childNode) {
    this.children.push(childNode);
  }
}

const root = new TreeNode('Root');
const child1 = new TreeNode('Child 1');
const child2 = new TreeNode('Child 2');
root.addChild(child1);
root.addChild(child2);

扁平数据转树形结构

当数据以扁平数组形式存储时,可以使用以下方法转换为树形结构。

function buildTree(items, id = null, link = 'parentId') {
  return items
    .filter(item => item[link] === id)
    .map(item => ({ ...item, children: buildTree(items, item.id) }));
}

const flatData = [
  { id: 1, name: 'Root', parentId: null },
  { id: 2, name: 'Child 1', parentId: 1 },
  { id: 3, name: 'Child 2', parentId: 1 },
  { id: 4, name: 'Grandchild', parentId: 2 }
];

const treeData = buildTree(flatData);

广度优先遍历(BFS)

与DFS不同,BFS逐层遍历树节点,适合需要按层级处理的场景。

js实现树形结构

function bfs(root) {
  const queue = [root];
  while (queue.length) {
    const node = queue.shift();
    console.log(node.value);
    node.children.forEach(child => {
      queue.push(child);
    });
  }
}

bfs(tree);

树形结构搜索

在树中搜索特定节点可以使用递归或迭代方法。

function searchTree(node, targetValue) {
  if (node.value === targetValue) return node;
  for (const child of node.children) {
    const found = searchTree(child, targetValue);
    if (found) return found;
  }
  return null;
}

const foundNode = searchTree(tree, 'Grandchild 2');

树形结构可视化

使用缩进来可视化树形结构可以方便调试和展示。

function printTree(node, indent = 0) {
  console.log(' '.repeat(indent) + node.value);
  node.children.forEach(child => {
    printTree(child, indent + 2);
  });
}

printTree(tree);

处理大型树的性能优化

对于大型树结构,可以考虑使用尾递归优化或迭代方法来避免堆栈溢出。

function traverseLargeTree(root) {
  const stack = [root];
  while (stack.length) {
    const node = stack.pop();
    console.log(node.value);
    for (let i = node.children.length - 1; i >= 0; i--) {
      stack.push(node.children[i]);
    }
  }
}

标签: 结构js
分享给朋友:

相关文章

js实现vue路由

js实现vue路由

Vue路由基础实现 使用Vue Router实现前端路由需要先安装并配置路由库。Vue Router是Vue.js官方的路由管理器。 安装Vue Router: npm install vue-r…

js实现预览

js实现预览

文件上传预览实现 使用JavaScript实现文件上传预览功能,可以通过FileReader对象读取文件内容并显示预览。以下代码支持图片、文本和PDF文件的预览: // HTML部分需要包含inpu…

js实现按钮点击

js实现按钮点击

实现按钮点击的JavaScript方法 HTML按钮元素 在HTML中创建按钮元素,为其添加id或class以便JavaScript选择: <button id="myButton">点…

js实现排序

js实现排序

数组排序方法 JavaScript提供了内置的sort()方法用于数组排序。默认情况下,sort()将元素转换为字符串并按照Unicode码点排序。对于数字排序,需传入比较函数。 const num…

js实现复选框

js实现复选框

实现复选框的基本方法 使用HTML的<input type="checkbox">元素创建复选框,并通过JavaScript监听其状态变化。 <input type="checkb…

js 实现验证码

js 实现验证码

实现验证码的 JavaScript 方法 生成随机验证码 验证码通常由随机字符(数字、字母或混合)组成。以下代码生成一个 6 位随机验证码(数字和字母混合): function generateCa…