我正在尝试用 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;
}