Is there a method to get the number of children in a TreeView object? I want to count all the children, including children's children, all the way down.
The getExpandedItemCount()
method only gets the child count of children who are expanded. Is there a way to get the count of all the children regardless of whether they are expanded or not.
There is a good reason not providing a method to count all children of a tree, as the expanded tree size might be VERY large or even infinite.
E.g.: It is possible to display a tree of all digits of a 'real' number:
But if you know what you do, and if the tree is limited in (expanded) size, you have to count by your own:
Use recursion, something like this:
To include the root within the tally, add 1:
Then just call the method giving the root as argument:
The solutions in this answer are overkill for just counting nodes in a small tree.
The simple recursive count solution in the other answers is fine. This answer is just provided to add a bit more context and alternate implementations.
On Stacks versus Recursion
When you use recursion, you are implicitly relying on the Java runtime to maintain a stack of items for you. For very large trees, this can be an issue, because the runtime can run out of stack space (a stack overflow).
For more information on preferring a stack over recursion see:
Of course, if you know the trees you are processing are small in size, it is OK to use recursion. Sometimes recursive algorithms are easier to understand than their non-recursive counterparts.
Iterator Based Solution
Example usage of the Iterator to count the items in a tree.
If desired, the iterator can be adapted to a stream, by creating a custom stream support class, which allows you to write functional code such as:
Sample program