Finding the Java implementation tree
I would like to implement and test a tree search function. I am using DefaultTreeModel javax.swing. I am working on my own Employee objects as tree data. I tried to get the following to work:
private DefaultMutableTreeNode search(int id, DefaultMutableTreeNode node){
if(node != null){
Employee emp = (Employee) node.getUserObject();
if(emp.getId() == id){
return node;
} else {
DefaultMutableTreeNode foundNode = search(id, node.getPreviousSibling());
if(foundNode == null) {
foundNode = search(id, node.getNextSibling());
}
return foundNode;
}
} else {
return null;
}
}
but it can only find an element that is among the parent siblings. And how to find it in the whole tree, from root to leaves. How to do it?
source to share
You can first go to the root of the tree in another method and then call your current recursive method.
private DefaultMutableTreeNode search(int id, DefaultMutableTreeNode node){
if(node == null){
return null;
}
node = node.getRoot(); //Turns out that this class has a getRoot() method.
return searchInternal(id,node); //Then does a depth-first search from the root node.
}
private DefaultMutableTreeNode searchInternal(int id, DefaultMutableTreeNode node){
if(node == null){ //I also switched this around, for good practice.
return null;
}
Employee emp = (Employee) node.getUserObject();
if(emp.getId() == id){ //Found it!
return node;
}
DefaultMutableTreeNode foundNode = searchInternal(id, node.getPreviousSibling());
if(foundNode == null) {
foundNode = search(id, node.getNextSibling());
}
return foundNode;
}
In general, recursive methods in Java are somewhat slower and prone to stack overflows. It is usually best to use your own depth-first search stack and this does not require any other method from you. Recursive methods can make your code more readable in some cases.
Which also works in this case:
private DefaultMutableTreeNode search(int id, DefaultMutableTreeNode node){
if(node == null){
return null;
}
Enumeration enumeration = node.getRoot().depthFirstEnumeration(); //Enumerate over all nodes in the tree.
while(enumeration.hasMoreElements()){
DefaultMutableTreeNode next = enumeration.next();
if(((Employee)next.getUserObject()).getId() == id){ //Found it!
return next;
}
}
return null;
}
It turns out that depth-first search is already implemented by Swing. However, this listing is after ordering. See the javadoc , there are methods for other types of workarounds as well.
source to share