开发者

k-ary Trees in Java

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.

I have a class of, say, W开发者_StackOverflowidget 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?


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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜