【问题标题】:Java implement tree searchJava实现树搜索
【发布时间】:2015-01-21 15:18:54
【问题描述】:

我想实现和测试一个树搜索功能。我正在使用 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;
    }
}

但它只能找到一个父级的兄弟姐妹中的元素。并且喜欢在整个树中找到它,从根到叶。我该怎么做?

【问题讨论】:

    标签: java search tree


    【解决方案1】:

    您可以先以不同的方法导航到树的根,然后调用您当前的递归方法。

    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,还有其他类型的遍历方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-04
      • 1970-01-01
      • 1970-01-01
      • 2015-07-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-20
      相关资源
      最近更新 更多