C++实现AVL树

标签 c++ avl-tree

我有一个 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);
}

和一个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;
    }
};

这是我在 TreeSet 中没有任何内容时添加函数的实现

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

主要函数:

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;
            }
        }
    }
}

但是当我有一个 txt 文件时 一个 4

它不会将 4 打印到屏幕上。你能帮我解决这个问题吗?

最佳答案

    AVLNode newNode(val);
    root = &newNode;      

newNode 是局部变量,您将指针指向此 var,但 newNodeadd 方法结束时超出范围,因此您有悬空指针。您需要通过 new 运算符在堆上分配 AVLNode:

    root = new AVLNode(val);      

关于C++实现AVL树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53680088/

相关文章:

c++ - 我应该如何使用remove_if删除两个数字范围内的元素

c++ - 使用 "virtual"关键字和不使用关键字覆盖函数

c++ - 如何以二进制方式读取和发送CR/LF "x0D x0A"

java - Java 中 TreeSet 方法的计算复杂性

c++ - 如何在不知道其父节点的情况下旋转子树

c++ - 如何为应用程序中的某些按钮重置 QApplication::styleSheet?

c++ - 错误 : Jump to case label in switch statement

c - AVL 树旋转。不同的可能性

algorithm - 有效地重新平衡 2^n-1 个节点的树?

algorithm - BST转换为对称结构的树