主题:[原创]非递归建立2叉树(请大家进来帮看看)
#include<stdio.h>
#include<malloc.h>
#define maxsize 50
typedef struct BtreeNode //树的结构体
{
char data;
struct BtreeNode *lchild;
struct BtreeNode *rchild;
}Btree;
typedef struct //栈的结构体
{
Btree *p[maxsize];
int top;
}Stack;
Stack *Creat_stack()//建立栈
{
Stack *s;
s=(Stack *)malloc(sizeof(Stack));
s->top=0;
return s;
}
int Empty_stack(Stack *s)//判断栈函数
{
if(s->top<0) return 1;
else return 0;
}
void Push_stack(Stack *s,Btree *x)//进栈函数
{
s->p[s->top]=x;
s->top++;
}
Btree *Pop_stack(Stack *s)//出栈函数
{
s->top--;
return s->p[s->top];
}
Btree *creatbtree()
{
Stack *s;
Btree *p,*q,*t;
char ch;
s=(Stack *)malloc(sizeof(Stack));
printf("按前序输入2叉树,以@代表空\n");
scanf("%c",&ch);
p=(Btree *)malloc(sizeof(Btree));
p->data=ch;
push(s,p);
t=p;
while(p!=NULL||!empty(s))
{
while(p!=NULL)
{
scanf("%c",&ch);
if(ch!='@')
{
q=(Btree *)malloc(sizeof(Btree));
q->data=ch;
p->lchild=q;
p=q;
push(s,q);
}
else
p->lchild=NULL;
}
if(!empty(s))
{
p=pop(s);
p=p->rchild;
}
}
return t;
}
还有剩余代码没写完,我的思路是按先序建2叉树.
由于才学数据有一些问题不懂,请大家帮忙看下有什么地方不对的请指出来!!! 谢谢了!~
#include<malloc.h>
#define maxsize 50
typedef struct BtreeNode //树的结构体
{
char data;
struct BtreeNode *lchild;
struct BtreeNode *rchild;
}Btree;
typedef struct //栈的结构体
{
Btree *p[maxsize];
int top;
}Stack;
Stack *Creat_stack()//建立栈
{
Stack *s;
s=(Stack *)malloc(sizeof(Stack));
s->top=0;
return s;
}
int Empty_stack(Stack *s)//判断栈函数
{
if(s->top<0) return 1;
else return 0;
}
void Push_stack(Stack *s,Btree *x)//进栈函数
{
s->p[s->top]=x;
s->top++;
}
Btree *Pop_stack(Stack *s)//出栈函数
{
s->top--;
return s->p[s->top];
}
Btree *creatbtree()
{
Stack *s;
Btree *p,*q,*t;
char ch;
s=(Stack *)malloc(sizeof(Stack));
printf("按前序输入2叉树,以@代表空\n");
scanf("%c",&ch);
p=(Btree *)malloc(sizeof(Btree));
p->data=ch;
push(s,p);
t=p;
while(p!=NULL||!empty(s))
{
while(p!=NULL)
{
scanf("%c",&ch);
if(ch!='@')
{
q=(Btree *)malloc(sizeof(Btree));
q->data=ch;
p->lchild=q;
p=q;
push(s,q);
}
else
p->lchild=NULL;
}
if(!empty(s))
{
p=pop(s);
p=p->rchild;
}
}
return t;
}
还有剩余代码没写完,我的思路是按先序建2叉树.
由于才学数据有一些问题不懂,请大家帮忙看下有什么地方不对的请指出来!!! 谢谢了!~