如何在Java中计算嵌套数据结构中的叶子节点?
我有一个类似这样的结构,我们称之为 Box 对象。
Box--+---Box----Box
|
+---Box-+--Box
|
+--Box
|
+--Box
我试图向顶部框对象询问叶节点框的列表,在本例中是 3 个框对象。
盒子对象在名为“children”的 Vector 类型实例变量中具有其子对象列表。
孩子的数量可以是无限的。
我一直在尝试编写一个递归方法来执行此操作,但没有成功。
I have a structure like this of what we'll call Box objects.
Box--+---Box----Box
|
+---Box-+--Box
|
+--Box
|
+--Box
I'm trying to ask the top box object for a list of the leaf node Boxes, which is the 3 box objects in this case.
The box object has a list of its children in an instance variable of type Vector called children.
The number of children can be unlimited.
I've been trying to write a single recursive method to do this, but without success.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
实现此目的的一种方法是递归遍历结构。思路如下:
您可以使用这种伪代码编写递归遍历:
希望这有帮助!
One way to do this would be a recursive traversal of the structure. The idea is as follows:
You could write a recursive traversal with this sort of pseudocode:
Hope this helps!
我已经有一段时间没有接触 Java 了,所以我确信这段代码有很多语法错误,我希望没有人因此而对我进行批评;只是想给你一些算法想法。希望它有帮助:
它遍历所有节点,将子节点添加到下一个列表中以进行检查,并将叶子添加到要返回的列表中。
it has been awhile since I've done Java, so I'm sure this code has plenty of syntax errors, and I hope no one marks me down for it; just trying to give you some algorithm ideas. Hopefully it helps:
It goes through all the nodes, adding children to the next list to check, and adding leaves to a list to be returned.
有多种方法可以编写这样的函数。这是一种解决方法。
另一种方法使用相同的深度优先遍历,但该函数将返回它发现的叶子列表。这些列表需要针对所探索的每组兄弟姐妹进行组合,并在每个函数调用返回时备份树。
There are several ways to write such a function. Here's one approach to work through.
A different approach uses the same depth-first traversal, but the function would return the list of leaves it discovered. These lists would need to be combined for each set of siblings explored, working back up the tree as each function call returns.