Duy Duy
Duy Duy

Reputation: 621

C++ implement AVL Tree

I have a TreeSet class describe a tree in c++:

class TreeSet
{
private:
    AVLNode * root;
    int count;

protected:
    void clearRec(AVLNode*root);


public:
    TreeSet();
    ~TreeSet();
    void clear();
    // print out the set in ascending order
    friend ostream& operator<<(ostream& os, const TreeSet& t);


    int add(int val);
}

and a AVL node class to represent an AVl node:

class AVLNode {
public:
    int key;            // data 
    AVLNode* left;      // left child
    AVLNode* right;     // right child
    int balance;        // balance factor

    AVLNode(int key) {
        this->key = key;
        left = right = NULL;
        balance = 0;
    }
    AVLNode(int key, int balance) {
        this->key = key;
        this->balance = balance;
        left = right = NULL;
    }
};

Here is my implementation for add function when there is nothing in TreeSet

int TreeSet::add(int val) {
    if (root == NULL) {
        AVLNode newNode(val);
        root = &newNode;        
        count++;
    }
}

The main function:

int main() {
    TreeSet set, temp, *subSet;
    ifstream ifs;
    ifs.open("input.txt");
    char command;
    int val;
    try
    {
        while (ifs >> command) {
            switch (command) {
            case 'a': // add an element to the set
                ifs >> val;
                set.add(val);
                break;
            }
        }
    }
}

But when I have a txt file with line a 4

it doesn't print out 4 to screen. Can you help me solving this?

Upvotes: 0

Views: 577

Answers (1)

rafix07
rafix07

Reputation: 20918

    AVLNode newNode(val);
    root = &newNode;      

newNode is local variable, you take the pointer to this var, but newNode goes out of scope at the end of add method, so you have dangling pointer. You need to allocate AVLNode on heap, by new operator:

    root = new AVLNode(val);      

Upvotes: 2

Related Questions