If you need a lot of access to a specific function of your data structure that is expensive to calculate, it may be advisable to pre-calculate it.
In the case of TreeNodes, this means that your TreeNodes will need to store their Child counter. Explain this in more detail: when creating node n0 this node has a child group ( cc ) equal to 0. When you add node n1 as a child of this, you are n1.cc + cc++ .
The complex bit is the delete operation. You must maintain parent backlinks and go up the hierarchy to subtract the cc your current node.
If you just want to use the hasChildren function for your nodes or override getChildCount , a logical element may be enough and will not force you to raise the entire hierarchy if deleted. Or you can remove backlinks and just say that you lose accuracy when deleting operations. The TreeNode interface TreeNode n't really force you to perform a delete operation, but you probably want to anyway.
Good thing the deal. In order to come up with pre-calculated exact values, you will need to maintain backlinks. If you do not, better call your hasHadChildren method or the more fun isVirgin .
source share