我正在尝试从元素向量创建一个 AVL 完美平衡的树。我已经开始使用少量元素(8),以便我可以检查算法的正确性。打印树中的值时出现我的问题,我不断收到下一个异常
"Exception thrown: read access violation. nod->stanga was 0x4."
当我到达 (root)->(right)->left-:value 时,即使我在打印任何内容之前检查指针是否为空。结构是:
typedef struct node
{ int key;
int size;
node *stanga;
node *dreapta;
}TreeNode;
数组:int vector[8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; 打印功能:
void printElements(TreeNode *nod)
{
if (nod != NULL)
{
printf("Nodul este : %d \n", nod->key);
if (nod->dreapta != NULL && nod->stanga != NULL)
{
printf("Nodul dreapta al nodului %d este : %d \n", nod->key, nod->dreapta->key);
printf("Nodul stamga al nodului este %d : %d\n ", nod->key, nod->stanga->key);
}
if (nod->dreapta != NULL)
{
printf("ramura dreapta a nodului %d cu valoare dreapta este : %d\n", nod->key,nod->dreapta->key);
printElements(nod->dreapta);
}
if (nod->stanga != NULL)
{
printf("ramura dreapta a nodului %d cu valoare stanga este : %d \n ",nod->key, nod->stanga->key);
printElements(nod->stanga);
}
}
else
{
printf("the end of the tree");
}
}
调用:
TreeNode *nod = (TreeNode*)malloc(sizeof(TreeNode));
nod=Build_tree(0, 7);
printElements(nod);
构建树是我的构建功能:
TreeNode* Build_tree(int start, int end)
{
if (start < end)
{
int medium = (start + end) / 2;
TreeNode *n1 = (TreeNode*)malloc(sizeof(TreeNode));
n1->key = vector[medium];
n1->size = 1;
if (n1->stanga == NULL)
{
n1->size = n1->dreapta->size + 1;//alocam sizeul nodului din drepata
}
if (n1->dreapta == NULL)
{
n1->size = n1->stanga->size + 1;//altefl alocam sizeul nodului din stanga
}
n1->stanga = Build_tree(start, medium-1);
n1->dreapta = Build_tree(medium+1,end);
return n1;
}
}
我对使用指针和平衡树有点生疏。有人可以帮助我提供线索吗?