java - DFS 一棵没有内存的树

标签 java algorithm tree

我正在尝试编写一个函数来通过深度优先搜索遍历树。

我目前的算法是这样的:

If children
 go to first child

If no children
 go to next sibling

If no siblings
 go to parent

我遇到的问题是我无法将树上的节点标记为已访问过,所以当我转到父节点时,循环会重置并再次转到子节点,陷入循环.有谁知道我该如何解决这个问题?

(它在 java 中使用 ANTLR 插件)

编辑:

按照我写的其中一条建议:

public void traverseTree(Tree tree){

    if (tree.getChildCount() > 0){
        tree = tree.getChild(0);
        traverseTree(tree);
        System.out.println(tree.toString());
    }
    if (tree.getParent().getChild(tree.getChildIndex() + 1) != null){
        tree = tree.getParent().getChild(tree.getChildIndex() + 1);
        traverseTree(tree);
        System.out.println(tree.toString());
    }
    if (!tree.getParent().toString().contains("ROOT_NODE")){
        tree = tree.getParent();
        traverseTree(tree);
        System.out.println(tree.toString());
    }
}

Root node 是根节点的名称,但我收到堆栈溢出错误。有人知道为什么吗?

谢谢。

最佳答案

在这种情况下我会使用递归。

class Node {
   public List<Node> getChildren() { .... }

   public void traverse(Visitor<Node> visitor) {
      // If children
      // go to first child - by traversing the children first.
       for(Node kid: getChildren())
           kid.traverse(visitor);
           // If no children
           //  go to next sibling, - by continuing the loop.

       visitor.visit(this);
       // If no siblings
       // go to parent - by returning and letting the parent be processed
   }
}


interface Vistor<N> {
   public void visit(N n);
}

关于java - DFS 一棵没有内存的树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9723085/

相关文章:

javascript - 为什么 div 中没有渲染 TreeView ,是 DOM 元素定位错误吗?

algorithm - 空间数据结构中的不同搜索方法

java - 一个数学函数可以让我们得到特定类型 k 元的叶子数量?

Java正则表达式匹配除可选后缀之外的贪婪数据

java - Java 中的通用枚举

Java:if 语句中的非运算符打印 "error"和正确的语句?

algorithm - 周期函数的渐近关系

Java去除ArrayList中的重复对象

python - 将罗马数字转换为整数

algorithm - 队列中的前 n 个元素