我正在尝试创建具有唯一指针的 AVL 树。但是我被困在递归插入节点的基本部分。insertNode_
此代码在调用函数时创建分段错误。我认为仅传递原始指针会起作用,但事实并非如此。
#ifndef AVL_H
#define AVL_H
#include <memory>
#include <iostream>
template<class T>
class AVL
{
public:
template<class K,class V>
struct nodeAVL;
typedef std::unique_ptr<nodeAVL<int,T>> node_ptr;
typedef nodeAVL<int,T> node;
/* Node struct */
template<class K,class V>
struct nodeAVL
{
nodeAVL(const K& key, const V& value):
key_ (key), value_ (value)
{ left = nullptr;right=nullptr;parent=nullptr; }
std::unique_ptr< nodeAVL<K,V> > left, right;
node* parent;
V value()
{ return value_; }
K key()
{ return key_; }
K key(const K& key)
{ key_ = key; }
private:
K key_;
V value_;
};
/* end of Node struct */
AVL()
{ head_=nullptr; };
void insert (const T& value)
{ std::cout<<value<<" inserting\n";
insertNode_ (head_, head_->parent,value); }
std::string print()
{ std::cout<<"print\n";
return print_inOrder_(head_, ""); }
private:
node_ptr head_;
template <class N, class... Args> //allows make_unique in c11
std::unique_ptr<N> make_unique(Args&&... args) {
return std::unique_ptr<N>(new N(std::forward<Args>(args)...));
}
/* recursive insertion */
void insertNode_( node_ptr& current,node* parent, const T& value)
{
std::cout<<"segmentation fault happens here, this line doesnt print\n";
if (current == nullptr){
current = std::move(make_unique<node>(-1,value));
std::cout<<current->value()<<" inserted\n";
if (parent!= nullptr)
std::cout<<"another issue happens here after root insertion\n";
}
else {
if ( current->value() > value )
insertNode_(current->left, current.get(),value);
else if ( current->value() < value )
insertNode_(current->right, current.get(),value);
}
}
/* recursive inOrder print */
std::string print_inOrder_(const node_ptr& current,std::string print)
{
if (current != nullptr) {
std::cout<<"<"<<current->value()<<">"<<std::endl;
print+= "[" + std::to_string(current->value())+"]";
print = print_inOrder_(current->left,print);
print = print_inOrder_(current->right,print);
}
return print;
}
};
#endif