数组转树

题目

实现一个函数,将input转成output

const input = [
  { id: "1", data: "中国", pid: null },
  { id: "2", data: "北京", pid: "1" },
  { id: "3", data: "上海", pid: "1" },
  { id: "4", data: "海淀", pid: "2" },
];

const output = [
  {
    id: "1",
    data: "中国",
    pid: null,
    children: [
      { id: "2", data: "北京", pid: "1", children: [{ id: "4", data: "海淀", pid: "2" }] },
      { id: "3", data: "上海", pid: "1" },
    ],
  },
];

答案

遍历方式:O(n²)

遍历优化:O(2n),提前将数组放到Map中

遍历再优化:O(n),在遍历过程中放到map中【推荐】

递归方式:

Last updated