Java中的k-ary树 [英] k-ary Trees in Java
问题描述
我在我的 Java 应用程序中有一个所谓的k-ary"树的非 UI 用途,并且想知道 javax.swing.tree 包是否是适合这项工作的工具,即使它与 Swing 一起打包.
I have a non-UI use for a so-called "k-ary" tree in my Java application and was wondering if the javax.swing.tree package was the right tool for the job, even though its packaged with Swing.
我有一类需要组织为树的 Widget 对象.这个 Widget 树的每个节点可以有 0+ 个子节点,因此它不一定是对称的.
I have a class of, say, Widget objects that need to be organized as a tree. Each node of this Widget tree can have 0+ children, and thus it is not necessarily symmetric.
我需要一个通用的树/节点结构,它允许我使用小部件或任何其他对象.具体来说,我需要一个(至少)执行后序遍历的遍历.
I need a generic Tree/Node structure that will allow me to use Widgets or any other object. Specifically, I need a traverse that does (at the very least) post-order traversals.
如果我没有找到正确的包裹,有人能指出我正确的方向吗?
If I'm not looking in the right package, can someone point me in the right direction?
推荐答案
虽然您可能能够设计该类来做您想做的事,但我觉得它与 JTree 比您想要的.Google 的普遍共识是,构建您自己的实现是一项快速且回报丰厚的练习 - 我能够在前几个结果中找到两种不同的实现.
While you might be able to finagle that class to do what you want, I get the sense that it's much more tightly coupled to JTree than you'd like. The general Google consensus is that building your own is a quick exercise that pays off well - I was able to find two different implementations in the top few results.
- http://vivin.net/2010/01/30/generic-n-ary-tree-in-java/
- http://sujitpal.blogspot.com/2006/05/java-data-structure-generic-tree.html
如果您有一些迫切需要自己动手,一般的想法是定义一个带有 List
子节点的 Node 类.然后你所要做的就是为诸如 insert
、delete
之类的事情提供你自己的方法.递归后序遍历就像做一个常规的二进制后序一样简单,除了left-right-root 您只需遍历对每个执行后序的子项列表,然后最后迭代根.
If you have some burning need to roll your own, the general idea is to define a Node class with a List<Node>
of children. Then all you have to do is provide your own methods for things like insert
, delete
, etc. Recursive postorder traversal is as simple as doing a regular binary postorder, except instead of left-right-root you simply walk the list of children doing postorder on each, then iterate the root last.
这篇关于Java中的k-ary树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!