获取树结构中从每个叶节点到根的路径
我怎样才能把这个树结构
[1, [2, [3, 4]], [5, [6, [7], 8]]]
1
2
3
4
5
6
7
8
....变成这个“反向树”结构,它基本上包含从所有叶节点到1(根)的路径:
[8, [5, [1]], 7, [6, [5, [1]]], 4, [2, [1]], 3, [2, [1]]]
8
5
1
7
6
5
1
4
2
1
3
2
1
结果甚至不必构建为树,四个按正确顺序排列的平面数组也可以。
看起来深度优先搜索可能是一个相关的算法,但我无法理解伪代码(incidentEdges()返回什么?),所以我很困惑。
如果有人可以提供 Ruby 方法(或者非常容易理解的伪代码)来将原始嵌套数组转换为结果数组,我将不胜感激。
这不是家庭作业,而是我学习以来时间太长的结果......我需要它以正确的顺序打印问题跟踪器中给定问题的依赖关系树。
How can I turn this tree structure
[1, [2, [3, 4]], [5, [6, [7], 8]]]
1
2
3
4
5
6
7
8
.... into this "reversed tree" structure, which basically contains the paths from all the leaf nodes to 1 (the root):
[8, [5, [1]], 7, [6, [5, [1]]], 4, [2, [1]], 3, [2, [1]]]
8
5
1
7
6
5
1
4
2
1
3
2
1
The result wouldn’t even have to be structured as a tree, four flat arrays in the correct order would also be fine.
It looks like Depth-first search might be a relevant algorithm, but I can’t understand the pseudocode (what does incidentEdges() return?), so I’m pretty stuck.
If someone could offer a Ruby method (or really easy to understand pseudocode) to convert the original nested array into the result array, I would be infinitely grateful.
And this is not a homework assignment, rather it is the result of it being too long since I’ve studied... I need this to print a dependency tree in the proper order for a given issue in an issue tracker.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更紧凑的代码:
A bit more compact code:
您可以使用此代码。这不是我最好的代码,但我也在学习 ruby :D (这是一个很好的练习)
You can use this code. It's not my best code, but I'm learning ruby too :D (it was a good exercise)
只是想一想,为什么不递归地遍历树,逐步连接节点,并在到达叶子时以相反的顺序输出节点。这应该会给你你想要的 4 个平面数组。
你的前 2 个叶子数组将像这样演变:
NWS
Just thinking off the top of my head, why not recusively traverse the tree progressively concatenating the nodes, and when you reach a leaf output the nodes in reverse order. This should give you the 4 flat arrays you wanted.
your first 2 leaf-arrays would evolve like this:
NWS
为了澄清我在之前对该问题的评论中试图表达的观点,我将展示一些代码。我只使用数组作为树,因此空树必须
[root, []]
(因此是空子树的守卫)。当然,这既不是您的输入,也不是您想要的结果;-) 但这是相同的想法,不是吗?我的观点是,如果数据结构是“逻辑”,那么代码应该非常简单(并且功能齐全,要遍历一棵树,我们不需要命令式算法!)。
To clarify the point I was trying to make in my previous comments to the question, I'll show some code. I use just an Array as tree, so the empty Tree must
[root, []]
(hence the guard for empty children).Granted, this is neither the input you had nor the the result you wanted ;-) but it's the same idea, isn't it? My point is that if the data structure is "logic", the code should be pretty straighforward (and functional, to walk a tree we shouldn't need an imperative algorithm!).