下面的代码让我很困惑。
班级
class AVLTree {
private:
struct AVLNode
{
AVLNode *leftchild;
AVLNode *rightchild;
int data;
int height;
};
AVLNode *root;
public:
AVLTree()
{
root = NULL;
}
bool isEmpty() const { return root == NULL; }
void print();
void inorder(AVLNode *n, int l);
void insert(int d);
void rotateLeft(AVLNode* n);
void rotateRight(AVLNode* n);
void rotateLeftTwice(AVLNode* n);
void rotateRightTwice(AVLNode* n);
AVLTree::AVLNode* insert(int d, AVLNode* n);
int max( int a, int b);
int height( AVLNode* n); };
插入功能。
AVLTree::AVLNode* AVLTree::insert(int d,AVLNode *n){
if (n == NULL)
{
AVLNode *n = new AVLNode;
n->data = d;
n->leftchild = NULL;
n->rightchild = NULL;
n->height = 0;
} else if( d < n->data) {
n->leftchild = insert(d,n->leftchild);
} else if (d > n->data) {
n->rightchild = insert(d,n->rightchild);
}
else {
n->height = max(height(n->leftchild), height(n->rightchild));
return n;
}
-----> This section of the code gives be "EXC_BAD_ACCESS".
n->height = max(height(n->leftchild), height(n->rightchild));
return n;
}
这是高度函数。
int AVLTree::height(AVLNode* node)
{ cout << "HEIGHT";
if(node == NULL)
{
return -1;
}
else {
return node->height;
}
}
有谁知道为什么?
=== 更新:
旋转时
void AVLTree::rotateLeft(AVLNode* n)
{
AVLNode *child = n->leftchild;
n->leftchild = child->rightchild;
child->rightchild = n;
n->height = max(height(n->leftchild),height(n->rightchild))+1;
child->height = max(height(child->leftchild),height(child->rightchild))+1;
n = child;
}
它似乎没有按应有的方式交换值。虽然 n = child 似乎在本地交换,但它并未反映其余代码的更改。给我一个无限循环。