js bfs与dfs遍历

256 阅读1分钟
      const tree = [
        {
          id: "a",
          children: [
            { id: "a1", children: [{ id: "a1-1" }, { id: "a1-2" }] },
            { id: "a2", children: [{ id: "a2-1" }, { id: "a2-2" }] },
          ],
        }
      ];
      // 深度优先遍历-递归版
      const dfs = (arr, res = []) => {
        if (!arr?.length) return;
        arr.forEach((item) => {
          res.push(item.id);
          deepD(item.children, res);
        });
        return res;
      };

      console.log(dfs(tree));
      // 深度优先遍历-非递归版
      const dfs1 = (arr) => {
        const quence = [...arr].reverse();
        const res = [];
        while (quence.length) {
          const item = quence.pop();
          res.push(item.id);

          if (!item.children) continue;
          for (let i = item.children.length; i--; i >= 0) {
            quence.push(item.children[i]);
          }
        }
        return res;
      };

      console.log(dfs1(tree));

      const bfs = (arr) => {
        const quence = [...arr];
        const res = [];
        while (quence.length) {
          const item = quence.shift();
          res.push(item.id);
          item?.children?.forEach(s => {
            quence.push(s);
          })
        }
        return res;
      };

      console.log(bfs(tree));