使用递归过滤树
我有一棵树,如下所示。
A1 B1 B2 A2 A3 B3 A4 A5 C1 C2 C3 A6
我想过滤这个返回
A1 A2 A3 A4 A5 A6
基本思想是只返回 A 节点。我遇到的困难是在 A2 的情况下我想删除 B1 并将 A2 拉到 B2 的级别
我正在使用 c# 树由节点列表组成
I have a tree that appears as follows.
A1 B1 B2 A2 A3 B3 A4 A5 C1 C2 C3 A6
I want to filter this to return
A1 A2 A3 A4 A5 A6
The basic idea is to only return A nodes. The struggle that I am having is in the case A2 I want to drop B1 and pull A2 up to the level of B2
I am using c# The tree is made up of List of Nodes
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您想要深度搜索(递归)并消除不是 A 的节点,对吗?
我会在返回时删除节点,将子节点插入到父节点(位于您当前所在节点的位置),然后每当您位于非 A 节点时删除该节点。
像这样的东西(简化的伪代码,在迭代节点集合时必须小心更改节点集合等):
You want to to a depth search (recursion) and eliminate nodes which aren't A's, right?
I'd remove the nodes on the way back, inserting the children to the parent (at the position of the node you're currently on) and then remove this node whenever you are on a non-A node.
Something like this (simplified pseudo-code, you have to be careful with changing node collections while they are being iterated etc.):
我假设您的树结构如下所示:
您可以使用单次深度优先搜索在单遍中过滤您的树。
我通常发现用函数式语言构建此类算法的原型,然后在需要时将它们转换为 C# 更容易。以下是 F# 代码:
以及 F# 输出:
以下是 C# 中的等效代码:
I'm going to assume your tree structure looks like this:
You can filter your tree in a single pass with a single depth first search.
I usually find it easier to prototype these sorts of algorithms in a functional language, then translate them to C# when needed. Here's the F# code:
And the F# output:
And here's the equivalent code in C#:
这是我在看到 Lucero 的解决方案之前想到的解决方案
This is the solution that I came up with before I saw Lucero's solution