Fast way of doing it is
Guid should point the object easily so that you can point nth node easily.
Generate a Single Random GUID
for eg : say 45892
Root node will point to that id.
child will point in the pattern Parent_ID+"-"+Index_Number
If consider three child will have 45892-0, 45892-1, 45892-2
And child of first node becomes - 45892-0-1, 45892-0-2
So you can travel directly using the id as faster and need not search, search time will be saved.
If you don't understand please comment. I will show in programming.
Note : ID length grows as depends on your level of usage.
If you have data already in the db or some persistent store.then you can prefer jgitter code. if not you can prefer this.
class Node {
public String id;
public String parentId;
public List<Node> childs;
}
class Operation {
public Node getChildNodeByID(Node root,String parentId) {
String[] keys = parentId.split("-");
Node parentNode = root;
int index = 0;
for(String key : keys ) {
if(index == 0) {
if( !root.id.equals(key) ) {
throw new IllegalArgumentException("Root node does not match so parent node will not be found in this node");
}
}else {
int myIndex = Integer.parseInt(key);
if( parentNode.childs.getSize() > myIndex ) {
parentNode = parentNode.childs.get(myIndex);
}else {
throw new IllegalArgumentException("Parent Node does not exist");
}
}
index++;
}
return parentNode;
}
public insert(Node node,Node root) {
Node parentNode = getChildNodeByID(root,node.parentId);
node.id = node.parentId+"-"+parentNode.childs.getSize();
parentNode.childs.add(node);
}
}