the code is in order to create a binary tree stored in a sequential structure, and to be able to traverse the binary tree in a previous order. However , when I create the binary tree, it can't output. Why is there a problem with the creation of binary trees? Is the struct has something wrong? please tell me how can I solve this problem? I will be appreciate you for what you have done.
#include <stdio.h>
#include <stdlib.h>
typedef struct node
{
int data;
struct node* left;
struct node* right;
}Tree;
typedef struct bit
{
Tree *a[100];
int length;
}Bitree;
typedef struct Stack
{
Tree *sq[1000];
int top;
}stack;
int empty(stack s)
{
return s.top==-1;
}
void push(stack *s,Tree *p)
{
s->sq[++s->top]=p;
}
void pop(stack *s)
{
if(s->top!=-1)
{
s->top--;
}
}
//return the top element
Tree *top(stack s)
{
if(s.top!=-1)
return s.sq[s.top];
}
Bitree *create(Bitree *tree1,int n)
{
int x;
tree1->a[0]->data=1;
printf("%d ",tree1->a[0]->data);
tree1->length=0;
printf("请输入根节点\n");
scanf("%d ",&x);
tree1->a[1]->data=x;
tree1->length++;
for(int i=2;i<=n;i++)
{
if(i%2==0)
{
printf("please input left binary tree\n");
scanf("%d ",&x);
tree1->a[i]->data=x;
tree1->a[i/2]->left=tree1->a[i];
tree1->length++;
}
else
{
printf("please input right binary tree\n");
scanf("%d ",&x);
tree1->a[i]->data=x;
tree1->a[i/2]->right=tree1->a[i];
tree1->length++;
}
}
return tree1;
}
void preorder1(Bitree *t)
{
stack s;
s.top=-1;
if(t->a[1]!=NULL) {
push(&s,t->a[1]);
}
while(!empty(s))
{
Tree *x=top(s);
pop(&s);
printf("%d ",x->data);
if(x->right!=NULL)
push(&s,x->right);
if(x->left!=NULL)
push(&s,x->left);
}
}
int main()
{
int n;
Bitree *t1;
scanf("%d",&n);
t1=create(t1,n);
preorder1(t1);
}