Josh Birdwell
Josh Birdwell

Reputation: 745

How to find Size & Height for a tree?

size of tree = number of nodes in tree

height of tree = the largest depth of the tree

I am implementing a tree in c++ with: class node private: list children; char* tag; int value;

Upvotes: 1

Views: 1592

Answers (1)

gomons
gomons

Reputation: 1976

If size is number of Element's children (direct and indirect) and element itself:

int Element::size(){
   if (children.empty())
     return 0;

   size_t size = 0;
   for (const auto &child : children)
      size += child->size();

   size += children.size();

   if (_depth == 0) return size + 1;
   else return size;
}

Upvotes: 1

Related Questions