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

#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);
}


 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值