Using a recursive data structure
It is impossible to iteratively traverse a recursive data structure, like a tree with pointers - this is because objects “hide” their underlying data elements.
Using a different data structure
All trees can be stored / implemented as linear, massive data structures, where indexes can be calculated using exponential mathematics:
For example, the tree [0, 1, 2, 3, null, 4, null] will describe a tree with 0 in the root, where 0 has direct children 1 and 2. And then 1 has the remaining child 3 ", and 2 left the child" 4 ".
Thus, if you store the tree in this way, the number of elements is, of course, the number of nonzero elements in the array.
Simply put: store the tree in a linear structure, and you can know the length at any time without creating any fantastic algorithm.
source share