前端算法,深度遍历和广度遍历

深度遍历

// 深度遍历
function deepEach(nodes) {
  if (!nodes.length) {
    return;
  }
  const arr = [];
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    console.log(node.name);
    arr.push(node);
    if (node?.children?.length) {
      arr.push(...deepEach(node.children));
    }
  }
  return arr;
}

广度遍历

// 广度遍历
function breadthEach(nodes) {
  if (!nodes.length) {
    return;
  }
  let arr = [];
  for (let i = 0; i < nodes.length; i++) {
    const node = nodes[i];
    arr.push(node);
    console.log(node.name);
    if (node?.children?.length) {
      nodes.push(...node.children);
    }
  }
  return arr;
}

数据结构

const list = [
  {
    name: "1",
    children: [
      {
        name: "1-1",
        children: [
          {
            name: "1-1-1",
          },
          {
            name: "1-1-2",
          },
        ],
      },
      {
        name: "1-2",
        children: [
          {
            name: "1-2-1",
          },
          {
            name: "1-2-2",
          },
        ],
      },
    ],
  },
  {
    name: "2",
    children: [
      {
        name: "2-1",
        children: [
          {
            name: "2-1-1",
          },
          {
            name: "2-1-2",
          },
        ],
      },
      {
        name: "2-2",
        children: [
          {
            name: "2-2-1",
          },
          {
            name: "2-2-2",
          },
        ],
      },
    ],
  },
];