#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
你觉得这部分怎么样?
line是树的级别(根有 line=0)
position是节点从左到右的位置(根的位置=0)