Reputation: 23
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, 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?
Upvotes: 2
Views: 4807
Reputation: 60140
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.
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.
Upvotes: 7