水中除油过滤器:求教由二叉树的前序遍历序列建立二叉树的非递归算法

来源:百度文库 编辑:神马品牌网 时间:2024/05/02 18:51:29
创建存储结构为二叉链表的二叉树,并按中序输出。创建时,以前序遍历顺序输入结点值,约定有效的结点值非0,0为空指针。请使用非递归方法实现。在C上做,我想要完整的代码,谢谢大家

#include <stdio.h> /*如发现bug请给我留言*/
#include <conio.h>
#include <stdlib.h>
#define LEN sizeof(struct node)
struct node
{
char data;
struct node *lchild,*rchild;
};
struct node *build()
{
struct node *stack[20]={NULL},*root,*temp,*p;
char c;
int i=-1;
c=getch();
if(c=='0')
return NULL;
root=p=(struct node *)malloc(LEN);
p->data=c;
c=getch();
while(1)
{
while(c!='0')
{
stack[++i]=p;
p=(struct node *)malloc(LEN);
p->data=c;
stack[i]->lchild=p;
c=getch();
}
p->lchild=NULL;
c=getch();
while(c=='0'&&i>=0)
{
p->rchild=NULL;
p=stack[i--];
c=getch();
}
if(c!='0')
{
temp=(struct node *)malloc(LEN);
p->rchild=temp;
temp->data=c;
p=temp;
c=getch();
}
else if(c=='0'&&i<0)
return root;
}
}
void output(struct node *head) /*中序输入出二叉树*/
{
struct node *stack[20],*p1=head;
int i=-1;
char c;
if(head==NULL)
return;
while(1)
{
while(p1->lchild!=NULL)
{
stack[++i]=p1;
p1=p1->lchild;
}
printf("%c",p1->data);
while(p1->rchild==NULL&&i>=0)
{
p1=stack[i--];
printf("%c",p1->data);
}

if(p1->rchild!=NULL)
{

p1=p1->rchild;

}
else if(p1->rchild==NULL&&i<0)
break;
}
}
int main(int argc, char *argv[])
{
struct node *head;
head=build();
output(head);
printf("\n");
return 0;
}