javascript 深度优先遍历和广度优先遍历

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",
          },
        ],
      },
    ],
  },
];

// 深度遍历
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 && 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 && node.children.length) {
      nodes.push(...node.children);
    }
  }
  return arr;
}
const liOne = breadthEach(list);
console.log(liOne);

const liTwo = breadthEach(list);
console.log(liTwo);

你可能感兴趣的:(javascript 深度优先遍历和广度优先遍历)