0

I am currently working on a program to implement a binary search tree. The struct for the tree is as follows:

struct treeNode {
    Type value;
    int count;
    treeNode* left;
    treeNode* right;
};
treeNode* root;

I am trying to implement the following function:

template <class Type>
int bstree<Type>::count(){

return count(root);
}

template <class Type>
int bstree<Type>::count(treeNode* sroot){


}

I am trying to figure out how I would visit every node and add up all the count values for each node.

Zack Herbert
  • 942
  • 1
  • 16
  • 39

3 Answers3

2
template <class Type>
int bstree<Type>::count(treeNode* sroot){
   int ret = 0;
   if ( sroot )
   {
      ret = sroot->count;
      ret += count(sroot->left);
      ret += count(sroot->right);
   }

   return ret;
}
R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • okay, I will try this. I am still struggling with recursion, so that I my biggest issue with figuring these methods out – Zack Herbert Apr 30 '15 at 20:03
1

I'm not sure why you're passing an argument... wouldn't this do it?

template <class Type>
int treeNode<Type>::get_count()
{
    int result = count;
    if (left) result += left->get_count();
    if (right) result += right->get_count();
    return result;
}

and then you call root->get_count();

RichieHindle
  • 272,464
  • 47
  • 358
  • 399
0

Some crazy C++ there

The only way I can see you could do it is to have a global variable which is updated by two callback functions, one goes left and the other right. You start at the first node. Each node you reach needs to result in a launch of another instance/thread of these functions. Recursion may be unsuitable because it could lead to a stack overflow. You need to create two new threads at each node to walk from the current tree node left and right. I had thought at first there was a chance of walking into a node more than once but now I realise that should never happen because a left right move will always take place at another level of the tree. I am assuming you have implemented the tree correctly because if you accidentally create a circular queue/list with pointers, welcome to infinity, unless you flag each value off that has been counted as suggested earlier.

I have not used C++ for years but you must be able to cast a pointer to list then you could cheat and not need any of the above just move through it sequentially.