Given this binary tree (actually, the binary tree can be random and dynamic, this is just an example...):
See link for the binary tree image: binary tree example
This are the given facts:
- All nodes are connected to their father so that we can traverse from bottom to top (and of course top to bottom too).
- All nodes hold information on how many descendants do they have in their left and right part.
The problem is this: I need to find a way to calculate the total number of nodes in level 2 (actually, in any level but for now, let's concentrate on level two). Obviously, the answer is 3 if we know the structure of the binary tree beforehand, but assume that we do not have this image, only the given facts.
Another catch here is we are going to start from a node that is in level 2 (our target level) and not the root. In this example, I've chosen NODE F.
I know that using the Breadth-first order traversal is the straight forward solution but I find it too time consuming since every time that I read a node, I will query it from a database.
I am looking for a more practical approach. But if it is "impossible" to solve this problem due to the insufficient given data, please let me know on what other data should be given in order for this to be solvable. I will assess it if it is feasible.
I am creating a website by the way and using PHP and MySQL. But I only want the concept or the explanation of the solution, more like an algorithm rather than a programming snippet or code...
I hope someone can answer me...Thank you very much!