my tree/node class:
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; } }
i know how traverse binary tree, traversing n-ary seems more tricky.
how go traversing through tree. want counter whilst traverse tree number/count each node in tree.
then @ specific count, can stop , return node @ count (perhaps remove subtree or add subtree @ position).
the simplest way implement visitor pattern this:
public interface visitor<t> { // returns true if visiting should cancelled @ point boolean accept(node<t> node); } public class node<t> { ... // returns true if visiting 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 can use this:
treeroot.visit(new visitor<type>() { public boolean accept(node<type> node) { system.out.println("visiting node "+node); return false; } });
or 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 "+visitor.getnode()); } else { system.out.println("tree has less 10 nodes"); }
Comments
Post a Comment