I am trying to implement a method to count all nodes of a tree from the root down. Basically I count the root then add the length of each of the roots child lists.
public int size()
{
int count = 1; //count the root node
for (int i = 0; i < root.getChildren().size(); i++){
count += (root.getChildren().get(i)).length() + 1;
}
return count;
}
This is the solved solution.
You can implement the
size()method as a member ofArrayTreeNode. Use recursion. The size for a node is 1 plus the sum of the children’s node sizes.So inside your
size()method you have two cases:If the node is a leaf, return 1. Here is no recursive call.
If the node has children, call the size() method of all the children, calculate the sum, add 1 for the node and return that value.
Btw. why do you have both
treeandrootattributes in classArrayTree? Isn’t a root node enough? Why do you have a separate classArrayTreeat all? AnArrayTreeNodefor itself is already a tree.Where do you set the
parentattribute of yourArrayTreeNodeclass? Wouldn’t it be best if you set the parent inside theaddChild()method to ensure thatparentis always valid?Update:
Ok, you asked for an example. I think if you are not used to recursion it’s not so easy to get your head around it.
This is a method of class
ArrayTreeNode: