I wrote a template class named "Tree<T>" in C++ which attributes are :
- T data
- std::vector<Tree*> sons;

I wrote the basic methods consisting of writing and reading in those two attributes. Now, I'm writing methods that return the min and max depth.

I have no compilation problems but when I test these methods on an example, I get false values. Here's the code for the minDepth and maxDepth methods (the other methods have names that make clear what they do) :

``````    int numberOfLevels() //we assume that this methode will be called on an initialized node
{
if (nbSons()==0) return 1;
std::vector<int> v;
for (int i=0;i<nbSons();i++) v.push_back(sons[i]->numberOfLevels());
return 1+max_v(v);
}

int maxDepth()
{
return numberOfLevels()-1;
}

int minDepth()
{
if (nbSons()==0) return 0;
std::vector<int> v;
for (int i=0;i<nbSons();i++) v.push_back(sons[i]->minDepth());
return 1+min_v(v);
}
``````

In the main, I define the tree shown in the attached picture, then I call min and max depth methods. Here's the main :

``````Tree<int>* root=new Tree<int>(1);
// Sons of node 0
// Son of node 01
// Sons of node 2
// Sons of node 20
//Son of node 200
std::cout<<"Minimum depth : "<<root->minDepth()<<std::endl;
std::cout<<"Maximum depth : "<<root->maxDepth()<<std::endl;
``````

I obtain :

Minimum depth : 1
Maximum depth : 3 (instead of 4)

I can't figure out why.

Why are you subtracting 1 on line 11?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.