我想实现并测试树搜索功能。我正在使用javax.swing的DefaultTreeModel。我在我自己定义的Employee对象上操作作为树数据。我试着让以下工作:
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;
}
}
但它只能找到一个父母的兄弟姐妹中的元素。并且喜欢在整个树中找到它,从根到叶。我该怎么做?
答案 0 :(得分:0)
您可以先使用其他方法导航到树的根,然后调用当前的递归方法。
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;
}
通常,递归方法在Java中运行速度稍慢,并且它们容易出现堆栈溢出。使用自定义堆栈进行深度优先搜索通常会更好,而且这并不需要您制作不同的方法。在某些情况下,递归方法可能会使代码更具可读性。
在这种情况下也有效:
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;
}
事实证明,Swing已经实现了深度优先搜索。这是一个后订单枚举。请参阅javadoc,还有其他类型的遍历方法。