Jen
Jen

Reputation: 255

Binary Tree, constructor

I am trying to pass a string to the constructor for a binary tree and for that first char to become the root. However, for whatever reason I can not assign that first value to the value of root and instead the whole program crashes. Anyone know why it's crashing?

  class PrefixTree
{
private:
    struct TreeNode
    {
        char character;
        TreeNode * left;
        TreeNode * right;
    };
    TreeNode* root;
public:

PrefixTree()
{
    root = NULL;
}
PrefixTree(string value)
{
    cout<<"wait";
    if (value[0] == '*')
    {
        cout << "Out 1"<<endl;
        root->character = value;
        cout << "Out 2"<<endl;
        root->left = NULL;
        cout << "Out 3"<<endl;
        root->right = NULL;
    }


}

and main:

   int main()
{

PrefixTree n("*abc");

 return 0;
 }

Upvotes: 0

Views: 512

Answers (1)

user1520427
user1520427

Reputation: 1365

You need to allocate memory for root, which you're not doing.

PrefixTree(string value)
{
   root = new TreeNode;
   // . . .
}

Also, don't forget to delete it in your destructor (and handle copies correctly).

Upvotes: 4

Related Questions