树类根节点未更新

Tree class root node not updating

本文关键字:更新 根节点      更新时间:2023-10-16

我正试图在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

我的Main函数是这样的:

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

请记住,即使在c++中,除非明确指定,否则参数通过值传递,因此:

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

加上this:

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 ===^

在声明和实现中都发生了变化。剩余的parent指针非声明的成员我留给你去修复,以及随后的内存泄漏从根节点的非销毁的孩子一旦你开始添加更多的节点到树。