层次创建二叉树及后序遍历

来源:互联网 发布:js for each 编辑:程序博客网 时间:2024/05/17 00:49

#include<stdio.h>
typedef struct node{
char ch;
struct node *lchild;
struct node *rchild;
}*tree;

typedef struct snode
{tree *bt;
struct snode *next;
int flag;
}stack;

typedef struct qnode{
tree *bt;
struct qnode *next;
}queue;

tree *creat()   /层次创建树
{tree *t ,*h,*root;
char c;
queue *front,*rear,*q;

h=(tree *)malloc(sizeof(tree));/创建队列的
h->ch='#';                       头节点
rear=(queue*)malloc(sizeof(queue));防止指针溢出
rear->bt=h;

front=q=rear;
root=(tree *)malloc(sizeof(tree));                                    /
scanf("%c",&c);
root->ch=c;
rear=(queue *)malloc(sizeof(queue));
rear->bt=root; /头节点入队列
q->next=rear;
q=rear;
while(front!=rear)
{front=front->next;
t=front->bt;/出队
scanf("%c",&c);
if(c=='0')t->lchild=NULL;
else{
t->lchild=(tree *)malloc(sizeof(tree));
t->lchild->ch=c;
rear=(queue *)malloc(sizeof(queue));
rear->bt=t->lchild;
q->next=rear;
q=rear;}
scanf("%c",&c);
if(c=='0')t->rchild=NULL;
else
{t->rchild=(tree*)malloc(sizeof(tree));
t->rchild->ch=c;
rear->bt=t->rchild;
q->next=rear;
q=rear;
 }
}
return root;}
        
void inorder(tree  *root) /后序遍历树
{stack *top=NULL,*s;
int f;
tree *p;
p=root;
if(root==NULL)return ;
while(p!=NULL||top!=NULl)
{if(p!=NULL)
{s=(stack *)malloc(sizeof(stack));
if(s==NULL)return;
s->bt=p;
s->flag=1;
s->next=top;
top=s;
p=p->lchild;
}
else{
s=top;
top=top->next;
p=s->bt;
f=s->flag;
if(f==1)
{s->next=top;/再入栈
top=s;
s->flag=2;
p=p->rchild;}
else
{printf("%3c",p->ch);
p=NULL;/防止进入死循环
free(s);/防止指针冲突
}
  }
    } 
        }
main()
{tree *root;
root=creat();
inorder(root);
}