树类根节点未更新

时间:2015-07-29 03:25:13

标签: c++ class binary-search-tree avl-tree root-node

我正在尝试用C ++编写一个AVL Tree类,我只是为正常的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;
}

1 个答案:

答案 0 :(得分: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指针未声明的成员,我留给你修复,以及一旦你开始向树中添加更多节点,随后的根节点的未被破坏的子节点的内存泄漏。

相关问题