当我尝试插入二叉搜索树时,我的程序出现分段错误。这是节点的声明:
template < class T > class binTreeNode {
friend class binTree < T >;
friend class binSTree < T >;
public:
// default constructor
binTreeNode ( const T& newData =T( ), binTreeNode < T >* newLeft = 0, binTreeNode < T >* newRight = 0 ) {
data = newData;
left = newLeft;
right = newRight;
}
private:
T data; // data value in node
binTreeNode < T > *left, *right; // links to other nodes
};
下面的函数都是新的,其他的(比如高度函数和构造函数)都是在父类中完成的,应该不相关。新功能是:
template <class T>
class binSTree : public binTree<T> {
public:
void insert (const T& newData) {
if (root == NULL) {
root = new binTreeNode<T>(newData);
}
else
insert(root,newData);
}
bool search (const T& x) const {
if (root != NULL)
return search(root,x);
else
return false;
}
bool remove (const T& x) {
if (root == NULL)
return false;
remove(root,x);
return true;
}
protected:
binTreeNode<T>* root;
private:
void insert (binTreeNode<T>*& ptr, const T& x) {
if (ptr == NULL) { // Base case, actual insertion
binTreeNode<T>* newNode;
newNode = new binTreeNode<T>(x);
ptr = newNode;
return;
}
if (x == ptr->data)
return;
else if (x < ptr->data)
insert(ptr->left,x);
else
insert(ptr->right,x);
return;
}
bool search (binTreeNode<T>* ptr, const T& x) const {
if (ptr->data == x)
return true;
else if (x < ptr->data && ptr->left != NULL)
search(ptr->left,x);
else if (ptr->right != NULL)
search(ptr->right,x);
else
return false;
}
binTreeNode<T>* remove (binTreeNode<T>* ptr, const T& x) {
if (ptr == NULL)
return NULL;
else if (ptr->data == x && leaf(ptr)) {
delete ptr;
ptr = NULL;
return ptr;
}
else if (ptr->data == x && !leaf(ptr))
return ptr;
else if (x < ptr->data) {
ptr->left = remove(ptr->left,x);
return ptr;
}
else {
ptr->right = remove(ptr->right,x);
return ptr;
}
}
bool leaf (binTreeNode<T>* node) const {
if (node->left != NULL || node->right != NULL)
return false;
return true;
}
};
根据 valgrind,分段错误出现在我检查 if (x == ptr->data) 的条件中的私有插入中。有谁知道这是为什么?我已经完全撞墙了。谢谢:3