小编ckr*_*use的帖子

使用parent_id从平面列表创建分层数据结构

我有一个这样的数据结构列表:

defmodule Foo do
  defstruct [:id, :parent_id, :children]
end

lst = [
  %Foo{id: 1, parent_id: nil, children: []},
  %Foo{id: 2, parent_id: 1, children: []},
  %Foo{id: 4, parent_id: 1, children: []},
  %Foo{id: 3, parent_id: 2, children: []},
]
Run Code Online (Sandbox Code Playgroud)

列表按parent_id和排序id,因此列表中较低的parent_ids比较低的s更早id.我想将该列表转换为分层数据结构:

  %Foo{id: 1, parent_id: nil, children: [
    %Foo{id: 2, parent_id: 1, children: [
      %Foo{id: 3, parent_id: 2, children: []},
    ]},
    %Foo{id: 4, parent_id: 1, children: []}
  ]}
Run Code Online (Sandbox Code Playgroud)

我对递归循环有一个天真的想法Enum.filter,但这看起来效率很低.任何想法如何有效地解决这个问题?

编辑:

我似乎有一个有效的解决方案,但它也是非常低效的:

defp build_tree(root, …
Run Code Online (Sandbox Code Playgroud)

elixir

2
推荐指数
1
解决办法
499
查看次数

标签 统计

elixir ×1