javasearchn-ary-tree

N-ary search tree in java with Comparable userObject?


So let's say I'm building a Tree using javax.swing.tree.DefaultMutableTreeNode and I add N children to a particular node. I want the children to be in a particular order (based on Comparable/a custom Comparator) like a search tree, even if I insert them out of order, like this:

node.insert(child2);
node.insert(child3);
node.insert(child1);

But DefaultMutableTreeNode doesn't do any kind of sorting like that. For my particular case, I even know the desired index of the child node in the parent's array, but I tried DefaultMutableTreeNode.insert and got a lot of ArrayIndexOutOfBoundsExceptions.

Can anyone recommend a library that does what I need? Or will I have to write a search tree like that myself?


Solution

  • Typically, you insert nodes in a tree so that it remains sorted for some traversal order. This depends on the tree's topology. You might get some implementation ideas from How to Use Trees, Creating a Data Model. In particular, "the "TreeModel interface accepts any kind of object as a tree node. It does not require that nodes be represented by DefaultMutableTreeNode objects, or even that nodes implement the TreeNode interface."