Like the title says, I want to count the nodes in for any given level of the tree. I already know how to make member functions for counting all the nodes of the tree, just not sure how to approach a specific level. Here's what I've tried. Any help is appreciated.
First parameter is a point to a character array inputted by the user. root is a private variable representing the "oldest" node.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
int TreeType::GetNodesAtLevel(ItemType* itemArray, int level)
{
TreeNode* p = root;
if (itemArray == NULL)
return;
if (level == 0)
{
cout << p->info << " ";
return;
}
else
{
GetNodesAtLevel(itemarray->left, level); //dereference in one and not the other was just testing
GetNodesAtLevel(*itemarray->right, level); //neither seems to work
}
}
What is ItemType?
You say you know how to count all the nodes, but that knowledge is not apparent here.
For example, using the root over and over again is kind of pointless.
ItemType is just an alias for char. And the knowledge isn't apparent there since I haven't included that function. Below is how I counted nodes in the whole tree.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int TreeType::GetLength() const
// Calls recursive function CountNodes to count the
// nodes in the tree.
{
return CountNodes(root);
}
int CountNodes(TreeNode* tree)
// Post: returns the number of nodes in the tree.
{
if (tree == NULL)
return 0;
elsereturn CountNodes(tree->left) + CountNodes(tree->right) + 1;
}
And the knowledge isn't apparent there since I haven't included that function.
Obviously that's not what I meant. I meant how could you screw up the current function so badly when you can apparently write the one in your last post? I assume someone else wrote that one for you. And someone else will need to write this one for you, too. But not me.
Not sure what you mean by "screwed" since both functions follow the same structure(the minor mistake being using the same root). My main issue was how to approach using an array of char, instead of a pre-built tree. But yeah "someone else" pointed me in the right direction, being queues. But thanks anyway.