How to Traverse a N-Ary Tree

≡放荡痞女 提交于 2019-12-05 18:04:43

The simplest way is to implement a Visitor pattern like this:

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

Now you can use it like this:

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

Or for your particular task:

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");
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!