id | name | father |
1 | N1 | null |
11 | N11 | 1 |
12 | N12 | 1 |
121 | N121 | 12 |
122 | N122 | 12 |
13 | N13 | 1 |
131 | N131 | 13 |
1311 | N1311 | 131 |
13111 | N13111 | 1311 |
14 | N14 | 1 |
2 | N2 | null |
public class Node {
def id
def name
def father
}
public class NodePrinter {
private void printLeftPad(def source,int pad)
{
for(int i=0;i<pad;i++) print " ";
println source;
}
public int indent(List items,int index,int pad)
{
printLeftPad("${items.get(index).name}",pad);
def current= items.get(index);
int i=index+1;
for(;i<items.size();i++)
{
if( items.get(i).father==current.id )
{
printLeftPad("{",pad);
i=indent(items,i,pad+4);
printLeftPad("}",pad);
}
else
{
if( current.father==items.get(i).father )
{
printLeftPad("${items.get(i).name}",pad);
current=items.get(i);
}
else
{
return i-1;
}
}
}
return i;
}
}
def nodes=[ new Node(id:1,name:'N1',father:null),
new Node(id:11,name:'N11',father:1),
new Node(id:12,name:'N12',father:1),
new Node(id:121,name:'N121',father:12),
new Node(id:122,name:'N122',father:12),
new Node(id:13,name:'N13',father:1),
new Node(id:131,name:'N131',father:13),
new Node(id:1311,name:'N1311',father:131),
new Node(id:13111,name:'N13111',father:1311),
new Node(id:14,name:'N14',father:1),
new Node(id:2,name:'N2',father:null)
];
def printer=new NodePrinter();
printer.indent(nodes,0,4);
This will give us the following result:
N1
{
N11
N12
{
N121
N122
}
N13
{
N131
{
N1311
{
N13111
}
}
}
N14
}
N2
Enjoy it!