我有一个家庭作业,要创建一个二进制搜索树类及其一些方法。现在,我被困在获取子树上。
这是我的节点类
template <typename T> //Node class
class Node {
T data;
Node<T> *left, *right;
public:
Node() {
left = right = nullptr;
};
T getData() {
return data;
}
void changeData(T newData);
void push(Node<T> *&root, T data);
void print(Node<T> *&root);
void cleanMemory(Node<T> *&root);
void map(Node<T> *&root, void (*f)(Node<T> *&root));
void deleteNode(Node<T> *&root, T key);
Node<T>* getSubTree(Node<T> *&root, T key);
void assembleTree(Node<T> *&var, Node<T> *&root, T Key);
};
和子树方法
template <typename T>
void Node<T>::assembleTree(Node<T> *&var, Node<T> *&root, T key) {
if (root != nullptr) {
if (root->data == key) {
var = root;
}
else {
var->assembleTree(var, root->right, key);
var->assembleTree(var, root->left, key);
}
}
}
template <typename T>
Node<T>* Node<T>::getSubTree(Node<T> *&root, T key) {
Node<T> *var = nullptr;
var->assembleTree(var, root, key);
return var;
}
问题出在我的程序清除内存时。控制台每次都会这样写:
Studying (lab3)(14723,0x1000b75c0) malloc: *** error for object 0x100503050: pointer being freed was not allocated
Studying (lab3)(14723,0x1000b75c0) malloc: *** set a breakpoint in malloc_error_break to debug
我要清除内存的代码:
template <typename T>
void Node<T>::cleanMemory(Node<T> *&root) {
if (root != nullptr) {
root->right->cleanMemory(root->right);
root->left->cleanMemory(root->left);
delete root;
root = nullptr;
}
}
删除“ root = nullptr”后,出现“线程1:EXC_BAD_ACCESS(code = EXC_I386_GPFLT)”错误