树类根节点未更新
Tree class root node not updating
我正试图在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
指针非声明的成员我留给你去修复,以及随后的内存泄漏从根节点的非销毁的孩子一旦你开始添加更多的节点到树。
相关文章:
- 使用 yaml-cpp 更新 YAML 文档的节点和值
- 使用 RapidXML 更新C++中的 XML 节点和属性值
- A*路径查找-如何有效地更新openNodes优先级队列中的节点值
- 无法更新属于列表中节点的对象中的值
- 如何递归删除Qt3DWindow根实体中的所有节点?
- 计算路径根到节点的总和等于一定数字的数量
- C++/RapidXML:编辑节点并写入新的 XML 文件没有更新的节点
- 想要以最新的添加节点完整返回树节点的根
- 插入功能保持重新创建根节点
- 根节点应具有分配的节点,但仍为 NULL。为什么我无法将节点分配给根?
- 为什么我的原始二叉搜索树被修改,即使我在另一个节点中复制了根节点
- 二进制搜索树中的根节点为空
- C++二叉树,修改根节点,指针到指针到根节点
- 是被视为列表一部分的单链列表的根节点
- c++ Boost属性树通过属性限定符更新现有节点
- 用c++更新XML节点值
- MPI:从进程渗透子数组来更新根/主进程中的主数组
- 删除二叉搜索树的根节点
- 将根节点替换为Document
- 树类根节点未更新