【发布时间】:2010-05-20 00:11:12
【问题描述】:
我有以下结构:
MyClass {
guid ID
guid ParentID
string Name
}
我想创建一个数组,其中包含元素按照它们应该在层次结构中显示的顺序(例如,根据它们的“左”值),以及一个将 guid 映射到缩进级别的哈希。
例如:
ID Name ParentID
------------------------
1 Cats 2
2 Animal NULL
3 Tiger 1
4 Book NULL
5 Airplane NULL
这基本上会产生以下对象:
// Array is an array of all the elements sorted by the way you would see them in a fully expanded tree
Array[0] = "Airplane"
Array[1] = "Animal"
Array[2] = "Cats"
Array[3] = "Tiger"
Array[4] = "Book"
// IndentationLevel is a hash of GUIDs to IndentationLevels.
IndentationLevel["1"] = 1
IndentationLevel["2"] = 0
IndentationLevel["3"] = 2
IndentationLevel["4"] = 0
IndentationLevel["5"] = 0
为了清楚起见,这是层次结构的样子:
Airplane
Animal
Cats
Tiger
Book
我想尽可能少地迭代项目。我也不想创建分层数据结构。我更喜欢使用数组、哈希、堆栈或队列。
两个目标是:
- 将 ID 的哈希存储到缩进级别。
- 根据所有对象的左值对包含所有对象的列表进行排序。
当我得到元素列表时,它们没有特定的顺序。兄弟姐妹应按其 Name 属性排序。
更新:这似乎是我自己没有尝试提出解决方案,只是希望其他人为我完成工作。但是,我尝试提出三种不同的解决方案,但我都陷入了困境。一个原因可能是我试图避免递归(可能是错误的)。我没有发布到目前为止的部分解决方案,因为它们不正确并且可能严重影响其他人的解决方案。
【问题讨论】:
-
递归数据需要递归解决方案。它们是递归解决方案存在的唯一原因。
-
并不总是需要递归,请参阅我的回答。
标签: algorithm language-agnostic hierarchical-data