C# 从上到下逐行递归遍历一棵树
最近一位朋友提出了一个有趣的问题:假设你有一个 List<节点类型>树中的所有节点。您将如何从根节点逐行遍历树,以便找到具有特定值的第一个节点。假设每个节点都有 3 个属性:名称/位置、父节点的身份以及谁“拥有”该节点。问题是你想要找到你“拥有”的树中的最高节点,无论它在哪个分支上。我了解基本逻辑,以便找到您查找以父集作为第一个节点的所有节点的第一组子集。但是您将如何递归地搜索 List<> ?的节点来找到你拥有的最高节点?
Interesting problem posed by a friend recently: Imagine you've got a List< NodeType > of all nodes in a tree. How would you go about traversing down the tree from the root node, by row such that you find the first node with a specific value. So say that each node has 3 attributes: its name/location, the identity of its parent, and who "owns" the node. The problem is you want to find the highest node in the tree that you "own" no matter what branch its on. I understand the basic logic in so much as to find the first set of children you look for all nodes with a parent set as the first node. But how would you go about recursively search through a List<> of nodes to find the highest node you own?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
更新:哈哈,哇,这是完全错误的,我刚刚意识到(因为它没有做你要求的事情)。没关系——无论如何,看起来你已经得到了正确的答案:)
我想我理解你的问题。如果我有什么问题请告诉我。
您有一个看起来像这样的
NodeType
类:首要任务是编写一个接受
NodeType
参数的函数,并给定一些可枚举的集合NodeType
对象,以递归方式返回其所有后代:下一步:编写一个函数,该函数接受
NodeType
对象并查找具有指定OwnerId
的最高后代>。这确实是一个非常简单的操作,所以我什至不会定义一个合适的函数;我将只使用 lambda:现在对于任何给定的 Id 值,找到最高匹配的
NodeType
是非常简单的:Update: Haha, wow, this is completely wrong, I just realized (as in it is not doing what you asked for). Never mind -- looks like you already got a correct answer, anyway :)
I think I understand your problem. Let me know if I'm getting something wrong.
You have a
NodeType
class that looks something like this:First order of business would be to write a function that takes a
NodeType
parameter and, given some enumerable collection ofNodeType
objects, returns all of its descendents in a recursive fashion:Next up: write a function that takes a
NodeType
object and finds the highest descendent with a specifiedOwnerId
. This is really a pretty simple operation, so I won't even define a proper function; I'll just use a lambda:Now for any given Id value, it is quite trivial to find the highest matching
NodeType
:算法:
Algorithm:
您正在寻找广度优先搜索。通常使用队列来实现:
You’re looking for breadth-first search. It is normally implemented using a queue: