0

我正在尝试用 C++ 编写一个 AVL 树类,我只是从为普通的 BST 编写代码开始,但我有一个问题。我遇到的问题是我的插入功能。我尝试将元素插入到树中,但实际上并没有这样做。我不太确定它为什么不这样做,我的直觉是我正在从函数中更改树,但我没有做任何事情来保存这些更改,我不知道该怎么做那。

#ifndef AVLTREE_H
#define AVLTREE_H
#include <iostream>

template <class K, class V>
struct AVLNode{
    K Key;
    V Value;
    AVLNode<K,V> *left;
    AVLNode<K,V> *right;
};

template <class K, class V>
class AVLTree{
    public:
        AVLTree();
        ~AVLTree();
        void insert(const K& Key, const V& Value);
        void print_AVL();
    private:
        void print_AVL2(AVLNode<K,V> *node);
        void insert2(AVLNode<K,V> *node, const K& Key, const V& Value);
        AVLNode<K,V> *root;
};

template <class K, class V>
AVLTree<K,V>::AVLTree(){
    root = nullptr;
}

template <class K, class V>
AVLTree<K,V>::~AVLTree(){
    delete root;
}
template <class K, class V>
void AVLTree<K,V>::insert(const K& Key, const V& Value){
    std::cout << "Trying to insert " << Key << ", " << Value << std::endl;
    insert2(root, Key, Value);
}

template <class K, class V>
void AVLTree<K,V>::insert2(AVLNode<K,V> *n, const K& Key, const V& Value){
    std::cout << n << std::endl;
    if(n== nullptr){
        n = new AVLNode<K,V>;
        n->Key = Key;
        n->Value = Value;
        n->parent = nullptr;
        n->left = nullptr;
        n->right = nullptr;
    }
    else if(n->Key > Key){
        insert2(n->left, Key, Value);
    }
    else{
        insert2(n->right, Key, Value);
    }
    std::cout << n << std::endl;
}

template <class K, class V>
void AVLTree<K,V>::print_AVL(){
    print_AVL2(root);
}


template <class K, class V>
void AVLTree<K,V>::print_AVL2(AVLNode<K,V> *n){
    std::cout << n << std::endl;
    if(n == nullptr){
        return;
    }
    print_AVL2(n->left);
    std::cout << "Name, ID: " << n->Value << ", " << n->Key << std::endl;
    print_AVL2(n->right);
}


#endif

我的主要功能如下所示:

#include "AVLTree.hpp"
#include <iostream>

int main() 
{
    AVLTree<std::string,std::string> Tree;
    Tree.insert("Hello","World");
    Tree.print_AVL();
    return 0;
}
4

1 回答 1

4

请记住,即使在 C++ 中,除非明确告知,否则参数是按值传递的因此:

void AVLTree<K,V>::insert2(AVLNode<K,V> *n, const K& Key, const V& Value)

再加上这个:

n = new AVLNode<K,V>;

只会将调用的结果分配new给一个自动变量,该变量n将在此函数返回时消失。

如果要保留该结果,请通过引用传递指针:

void AVLTree<K,V>::insert2(AVLNode<K,V>*& n, const K& Key, const V& Value)
// reference to the caller's pointer ===^

在 decl 和实现中都发生了变化。剩下的parent指针未声明成员我留给您修复,以及一旦您开始向树中添加更多节点,根节点的未销毁子节点会导致内存泄漏。

于 2015-07-29T03:42:14.947 回答