T = int*
你说你想要一个
T*
(即
int**
)在
T* key
所以当你试图提供一个
int*
我建议更改
Node
T
而不是
T*
:
template <class T>
class Node {
public:
Node* left;
T data; // not T*
Node* right;
int height;
};
template <class T>
class AVLTree {
public:
Node<T>* root;
Node<T>* insert(Node<T>* p, T* key) {
Node<T>* t;
if (p == nullptr) {
t = new Node<T>;
t->data = *key;
t->left = nullptr;
t->right = nullptr;
t->height = 1;
return t;
}
if (*key < p->data) {
p->left = insert(p->left, key);
} else if (*key > p->data) {
p->right = insert(p->right, key);
}
return p;
}
};
然后实例化一个
AVLTree<int>
而不是
AVLTree<int*>
这里有一个建议,可以存储指针并使用
std::less
和
std::greater
#include <functional>
template <class T>
class Node {
public:
Node* left;
T data;
Node* right;
int height;
};
template <class T>
class AVLTree {
public:
Node<T>* root;
Node<T>* insert(Node<T>* p, const T& key) { // key is an int*& in this example
Node<T>* t;
if (p == nullptr) {
t = new Node<T>;
t->data = key;
t->left = nullptr;
t->right = nullptr;
t->height = 1;
return t;
}
if (std::less<T>{}(key, p->data)) { // less
p->left = insert(p->left, key);
} else if (std::greater<T>{}(key, p->data)) { // greater
p->right = insert(p->right, key);
}
return p;
}
};
int main() {
AVLTree<int*> tree1;
int a = 5;
int* ap = &a;
tree1.root = tree1.insert(tree1.root, ap);
}