well, each node should be represented by a node_id in a DB or whatever file U use and this should know (store) the id of its parent, so you can't mess up things. And btw, there is
to let anode know if it has children or not. If there are children THEY WILL KNOW their parent. Keep it simple: stupid. :-)
btw BmeCat works this way and made it to a standard.