0

I am doing a a question in the book that asks me to write constructor and copy-control members for a class that has following variables. Can someone gimme a scenario/example where this class is useful? possible some codes in main function? The part I got confused is that why it needs TreeNode* left and TreeNode* right. I cannot think of the use of them.

#include <iostream>
#include <string>
using namespace std;
class TreeNode
{
public:
    //constructor
    TreeNode(const string& s, const int& n, const TreeNode& lm, const TreeNode& rm):
        value(s), count(n), left(new TreeNode(lm)), right(new TreeNode(rm)) {}
    //copy-constructor
    TreeNode(const TreeNode& m): value(m.value), count(m.count), left(new TreeNode(*m.left)), right(new TreeNode(*m.right)) {}
    //assignment operator
    TreeNode& operator=(const TreeNode& m)
    {
        value = m.value;
        count = m.count;
        *left = *m.left;
        *right = *m.right;
        return *this;   
    }
    //destructor
    ~TreeNode()
        {
      delete left;
      delete right;
    }
private:
    string value;
    int count;
    TreeNode *left;
    TreeNode *right;
};
int main ()
{
    return 0;
}
ihm
  • 1,833
  • 2
  • 18
  • 23

1 Answers1

6

You could use this class to store elements from a binary tree (see http://en.wikipedia.org/wiki/Binary_tree) in which case the left and right members probably make sense.

Binary trees are for instance used for storing data in an ordered way. While inserting elements is potentially costly, looking up an element is pretty fast with a complexity of O(log n).

BjoernD
  • 4,720
  • 27
  • 32
  • @ihm: binary search trees, or their smarter cousins, are in the C++ library under the names `std::set` and `std::map`. – Fred Foo Nov 23 '11 at 16:23