当前位置:首页 > 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实现pdf在线预览

js实现pdf在线预览

使用PDF.js实现PDF在线预览 PDF.js是由Mozilla开发的一个开源JavaScript库,可以在网页中直接渲染PDF文件。以下是实现PDF在线预览的步骤: 引入PDF.js库 在HT…

js实现抽奖

js实现抽奖

实现抽奖功能的基本思路 抽奖功能的核心是随机选择奖项并展示结果。可以通过数组存储奖项,利用随机数生成索引,最后通过动画增强用户体验。 准备奖项数据 定义一个数组存储奖项信息,每个奖项可以包含名称、图…

js实现vue路由

js实现vue路由

Vue 路由的基本实现 在 Vue.js 中实现路由功能通常使用 Vue Router 库。Vue Router 是 Vue.js 官方的路由管理器,用于构建单页面应用(SPA)。 安装 Vue R…

js实现密码

js实现密码

密码强度验证 使用正则表达式验证密码强度是一种常见方法。以下代码检查密码是否包含大小写字母、数字和特殊字符,且长度至少为8位: function checkPasswordStrength(pass…

js实现正交

js实现正交

正交的概念 正交在数学和计算机科学中通常指两个向量垂直或线性无关。在编程中,正交性常被用于设计模块化、低耦合的系统。 向量正交判断 判断两个向量是否正交可以通过点积是否为0来实现: functio…

js实现上传图片

js实现上传图片

使用HTML5的File API实现图片上传 HTML5的File API允许通过JavaScript访问用户选择的文件。需要创建一个文件输入元素,并监听其change事件。 <input t…