我正在尝试为C ++中的二进制搜索树编写模板程序。我能够轻松编写搜索,插入和有序遍历函数。当我尝试编写用于delete(delNodeUtil())功能的代码时,出现了一个错误。
1>------ Build started: Project: binarySearchTree, Configuration: Debug Win32 ------
1>binarySearchTree.cpp
1>bst.h(116): error C2988: unrecognizable template declaration/definition
1>bst.h(116): error C2143: syntax error: missing ';' before '*'
1>bst.h(116): error C2065: 'T': undeclared identifier
1>bst.h(116): error C2923: 'BST': 'T' is not a valid template type argument for parameter 'T'
1>bst.h(116): error C2903: 'BST': symbol is neither a class template nor a function template
1>bst.h(116): error C2061: syntax error: identifier 'T'
1>bst.h(117): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>bst.h(117): error C2059: syntax error: '{'
1>bst.h(117): error C2143: syntax error: missing ';' before '{'
1>bst.h(117): error C2447: '{': missing function header (old-style formal list?)
1>Done building project "binarySearchTree.vcxproj" -- FAILED.
我不明白为什么在这种情况下无法识别我的模板。
#ifndef BST_H_
#define BST_H_
#include <iostream>
using namespace std;
template<class T>
class BST {
private:
struct Node {
T data;
Node *right = NULL;
Node *left = NULL;
};
Node *root;
void inOrderUtil(Node *n);
struct Node* delNodeUtil(Node *n,T d);
public:
BST(T d);
void insertNode(T d);
bool search(T d);
void inOrder();
void delNode(T d);
};
template<class T>
BST<T>::BST(T d) {
root = new Node;
root->data = d;
root->left = NULL;
root->right = NULL;
}
template<class T>
void BST<T>::insertNode(T d) {
Node *n = new Node;
n->data = d;
if (root == NULL) {
root = n;
return;
}
Node *current = root;
while (true) {
if (d < current->data) {
if (current->left == NULL) {
current->left = n;
break;
}
else {
current = current->left;
}
}
else {
if (d > current->data) {
if (current->right == NULL) {
current->right = n;
break;
}
else {
current = current->right;
}
}
}
}
}
template<class T>
bool BST<T>::search(T d) {
if (root->data == d) {
return true;
}
Node *current = root;
while (current != NULL) {
if (d < current->data) {
current = current->left;
}
else {
if (d > current->data) {
current = current->right;
}
else {
return true;
}
}
}
return false;
}
template<class T>
void BST<T>::inOrder() {
if (root != NULL) {
cout << "Inorder traversal is: ";
inOrderUtil(root);
cout << endl;
}
else {
cout << "Tree is empty" << endl;
}
}
template<class T>
void BST<T>::inOrderUtil(Node *n) {
if (n != NULL) {
inOrderUtil(n->left);
cout << n->data << " ";
inOrderUtil(n->right);
}
}
template<class T>
struct Node * BST<T>::delNodeUtil(Node * n, T d)
{
return NULL;
}
template<class T>
void BST<T>::delNode(T d) {
if (root->data == NULL) {
cout << "Tree is empty" << endl;
return;
}
root = delNodeUtil(root, d);
}
#endif
我还没有为delNodeUtil函数编写内容。这是我收到上述错误的地方。我希望有人能找出上面代码中我在做什么错。谢谢