如何遍历一棵N叉树

4

我的树/节点类:

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叉树似乎更加棘手。

我该如何遍历这棵树。在遍历树的过程中,我想要一个计数器来计算树中的每个节点数量。

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

1个回答

3
最简单的方法是实现访问者模式,如下所示:

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");
}

访问者模式可能有点过度设计,因为我们只处理一种类型的节点。 - Henry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接