java - 如何遍历 N 叉树

标签 java algorithm tree nodes traversal

我的树/节点类:

import java.util.ArrayList;
import java.util.List;

public class Node<T> {
   private T data;
   private List<Node<T>> children;
   private Node<T> parent;

   public Node(T data) {
      this.data = data;
      this.children = new ArrayList<Node<T>>();
   }

   public Node(Node<T> node) {
      this.data = (T) node.getData();
      children = new ArrayList<Node<T>>();
   }

   public void addChild(Node<T> child) {
      child.setParent(this);
      children.add(child);
   }

   public T getData() {
      return this.data;
   }

   public void setData(T data) {
      this.data = data;
   }

   public Node<T> getParent() {
      return this.parent;
   }

   public void setParent(Node<T> parent) {
      this.parent = parent;
   }

   public List<Node<T>> getChildren() {
      return this.children;
   }
}

我知道如何遍历二叉树,但遍历 N 元树似乎要棘手得多。

我将如何遍历这棵树。我想要一个计数器,同时遍历树以对树中的每个节点进行编号/计数。

然后在特定计数时,我可以停止并返回该计数的节点(可能删除该子树或在该位置添加子树)。

最佳答案

最简单的方法是实现这样的访问者模式:

public interface Visitor<T> {
    // returns true if visiting should be cancelled at this point
    boolean accept(Node<T> node);
}

public class Node<T> {
    ...

   // returns true if visiting was cancelled
   public boolean visit(Visitor<T> visitor) {
       if(visitor.accept(this))
           return true;
       for(Node<T> child : children) {
           if(child.visit(visitor))
               return true;
       }
       return false;
   }
}

现在你可以像这样使用它:

treeRoot.visit(new Visitor<Type>() {
    public boolean accept(Node<Type> node) {
        System.out.println("Visiting node "+node);
        return false;
    }
});

或针对您的特定任务:

class CountVisitor<T> implements Visitor<T> {
    int limit;
    Node<T> node;

    public CountVisitor(int limit) {
        this.limit = limit;
    }

    public boolean accept(Node<T> node) {
        if(--limit == 0) {
            this.node = node;
            return true;
        }
        return false;
    }

    public Node<T> getNode() {
        return node;
    }
}

CountVisitor<T> visitor = new CountVisitor<>(10);
if(treeRoot.visit(visitor)) {
    System.out.println("Node#10 is "+visitor.getNode());
} else {
    System.out.println("Tree has less than 10 nodes");
}

关于java - 如何遍历 N 叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32795799/

相关文章:

用于 mini-max 算法的 Java 动态树

java - Querydsl - 如何在选择表达式中连接多个列的值?

java - 可嵌入 PK 对象在持久和刷新后未填充

php - 获取特定数字的所有变体特定长度和特定最小值和最大值?

python - "Find the longest substring with k-unique characters"的时间复杂度?

clojure - Clojure 中的树遍历

java - 为什么我在 if 语句中定义 double 时遇到问题?

java - 以非交互方式将多行标准输入传递给交互式 Java 命令行程序

performance - 邻接矩阵的速度提升

sql - 在邻接表中查找后代的根节点