まず、ノードとツリーデータ構造を作成します。
Node:
Node(String value)
Tree
Tree(Node node) : Creates a tree with root as node
Node getNode(Node node, String nodeToRetrive) nodeToRetrive will be a child of node
returns null if not found
Node addNode(Node node, String nodeToBeAdded) nodeToBeAdded will be added as a new child of node and the newly added Node would be returned
ルートをAとしてツリーを作成します。
Node root=new Node("A");
Tree tree=new Tree(root);
入力文字列を「_」でトークンに分割します。たとえば、「A_AChild_furtherChild」は「A」、「AChild」、「furtherChild」に分割されます。
String s="A_AChild_furtherChild";
String[] tokens=s.split("_");
2番目(この場合は「AChild」)から始まるトークンをループし、必要な処理を実行します。
Node node=tree.root; Node n;
for( i=1 ;i <tokens.length; i++){
n=getNode(node,tokens[i]);
if(n==null){
n=addNode(node,tokens[i]);
}
node=n;
}
上記のループを使用して、ツリー全体を構築できます。
ツリー内のノードの値を再帰的に取得します。
public void printTree(Node n, int level){
display level number of spaces and print the value held by Node n.
for(each of the children of n){
printTree(theChild, level+1)
}
}
上記の再帰メソッドは、最初は次の方法で呼び出されます。
printTree(root,0);