#include <stdio.h>
#include <stdlib.h>
typedef struct nod{
int data;
struct nod *left,*right;
}NOD;
NOD * generate(NOD * root)
{
NOD *r,*p;
int d=-1,value,line,position,i,f,v;
if(root==NULL)
{
do{
printf("Would you like to create the root node?\n\n1 - yes\n0 - no\n");
scanf("%d",&d);
switch(d)
{
case 1:
printf("Value=");
scanf("%d",&value);
root=add_root(value);
break;
case 0:
return NULL;
break;
default:
printf("Command unrecognized!\n");
break;
}
} while(d==-1);
if(root!=NULL)
printf("Root node successfully created!\n");
else
printf("Error: could not create root node!\n");
d=-1;
do{
printf("Continue adding nodes?\n\n1 - yes\n0 - no\n");
scanf("%d",&d);
switch(d)
{
case 1:
printf("Insert the line and the position of the node you wish to add (root node has line=0, position=0)\nLine=");
scanf("%d",&line);
printf("Position (less or equal with 2^$line-1)=");
scanf("%d",&position);
printf("Value=");
scanf("%d",&value);
r=p=root;
for(i=line-1;i=0;i--)
{
f=power(2,i);
if(position & f == f) // if the i-(st,nd,rd,th) bit of "position" is 1, then (position & f == f) is true and *r will go right
{
p=r;
r=r->right;
v=1;
}
else
{
p=r;
r=r->left;
v=0;
}
}
if(v==0)
p=add_left(&r,value);
if(v==1)
p=add_right(&r,value);
break;
case 0:
return root;
break;
default:
printf("Command unrecognized!\n");
break;
}
} while(d==-1);
}
else
{
...
}
NOD * add_left(NOD **p,int value)
{
NOD * r;
r=malloc(sizeof(NOD));
r->data=value;
r->left=NULL;
r->right=NULL;
(*p)->left=r;
return r;
}
NOD * add_right(NOD **p,int value)
{
NOD * r;
r=malloc(sizeof(NOD));
r->data=value;
r->left=NULL;
r->right=NULL;
(*p)->right=r;
return r;
}
NOD * add_root(int value)
{
NOD * x;
x=malloc(sizeof(NOD));
x->data=value;
x->left=NULL;
x->right=NULL;
return x;
}
}
int main() {
NOD *root=NULL;
root=generate(root);
return 0;
}
我試圖做的是創建一個二叉樹的程序,但我不斷收到SIGSEGV段錯誤,我不明白爲什麼。你能告訴我我做錯了什麼嗎?二叉樹 - 分段故障
if(position & f == f) // if the i-(st,nd,rd,th) bit of "*position*" is 1,
// then (position & f == f) is true and *r will go right
您對這部分有什麼看法?
線是樹的級別(根部具有線= 0)
位置是節點的位置從左至右(根部具有位置= 0)
請儘量縮小問題,並使用調試器。就目前而言,這是很多代碼,可能會導致對C的基本原理的一些基本誤解,或者可能是一個簡單的錯誤。 –