I’m writing a binary tree class, and I’m stuck on a levelCount method, where I need to count the number of nodes on a level of the tree. The class and method look something like this:
public class ConsTree<T> extends BinaryTree<T>
{
BinaryTree<T> left;
BinaryTree<T> right;
T data;
public int levelCount(int level)
{
}
}
So the idea is that each tree has a tree to its left, a tree to its right, and data. There is an abstract class binarytree and subclasses ConsTree and EmptyTree.
I think I need to use a breadth first search and count the number of nodes once I get to that level, but I’m stuck on how to start. Any guidance here would be helpful. I can provide any other info necessary.
Here’s the general approach.
You traverse the tree exactly as you would normally (depth-first, in-order) but you simply pass down the desired and actual level as well, with pseudo-code such as:
It doesn’t actually traverse the entire tree since, once it gets to the desired level, it can just ignore everything underneath that. Here’s a complete C program that shows this in action:
It builds a tree of the following form (where
Tmeans top,Lis a left branch andRis a right branch):If you compile and run that code, you’ll see it gives the correct node count at each level: