递归算法(时间复杂度O(2^n))

  1. /**
  2. * 递归查找,获取children
  3. */
  4. const getChildren = (data, result, pid) => {
  5. for (const item of data) {
  6. if (item.pid === pid) {
  7. const newItem = {...item, children: []};
  8. result.push(newItem);
  9. getChildren(data, newItem.children, item.id);
  10. }
  11. }
  12. }
  13. /**
  14. * 转换方法
  15. */
  16. const arrayToTree = (data, pid) => {
  17. const result = [];
  18. getChildren(data, result, pid)
  19. return result;
  20. }

最优算法

  1. function arrayToTree(items) {
  2. const result = []; // 存放结果集
  3. const itemMap = {}; //
  4. for (const item of items) {
  5. const id = item.id;
  6. const pid = item.pid;
  7. if (!itemMap[id]) {
  8. itemMap[id] = {
  9. children: [],
  10. }
  11. }
  12. itemMap[id] = {
  13. ...item,
  14. children: itemMap[id]['children']
  15. }
  16. const treeItem = itemMap[id];
  17. if (pid === 0) {
  18. result.push(treeItem);
  19. } else {
  20. if (!itemMap[pid]) {
  21. itemMap[pid] = {
  22. children: [],
  23. }
  24. }
  25. itemMap[pid].children.push(treeItem)
  26. }
  27. }
  28. return result;
  29. }