简体   繁体   English

C ++实现AVL树

[英]C++ implement AVL Tree

I have a TreeSet class describe a tree in c++: 我有一个TreeSet类,用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: 以及表示AVl节点的AVL节点类:

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 这是我在TreeSet中没有任何内容时对add函数的实现

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 但是当我有第4行的txt文件时

it doesn't print out 4 to screen. 它不会在屏幕上打印出4。 Can you help me solving this? 你能帮我解决这个问题吗?

    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. newNode是局部变量,您可以使用指向此var的指针,但是newNodeadd方法的末尾超出了作用域,因此您有悬空的指针。 You need to allocate AVLNode on heap, by new operator: 您需要通过new运算符在堆上分配AVLNode:

    root = new AVLNode(val);      

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM