//自下而上,自右往左层次遍历
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
#define Max 10
typedef struct treenode {
char data;
struct treenode* lchild, * rchild;
}treenode,*tree;
//前序构造二叉树..通过输入来构造
void creatTree(tree& t) {
char ch;
ch = getchar();
if (ch == '#') t = NULL;
else {
t = (treenode*)malloc(sizeof(treenode));
t->data = ch;
t->lchild = NULL;
t->rchild = NULL;
creatTree(t->lchild);
creatTree(t->rchild);
}
}
//写进栈出栈判空判满;
typedef struct stack1 {
struct treenode* data[Max];
int top=-1;
}stack1;
bool IsEmpty(stack1 s) {//栈判空
if (s.top == -1) return true;
return false;
}
bool Isfull(stack1 s) {//栈判满
if (s.top == Max - 1) return true;
return false;
}
bool push(stack1& s, treenode* p) {//进栈
if (s.top == Max - 1) {
printf("站满");
return false;
}
s.data[++s.top] = p;
return true;
}
bool pop(stack1 &s, treenode*& p) {//出栈
if(s.top==-1) {
printf("站kong");
return false;
}
p = s.data[s.top--];
return true;
}
//进队出队判空判满
typedef struct queue1 {
struct treenode* data[Max];
int front=0;
int rear=0;
};
bool isqueueEmpty(queue1 q) {
if (q.front == q.rear)return true;
return false;
}
bool isqueuefull(queue1 q) {
if (q.front == (q.rear + 1) % Max)return true;
return false;
}
bool enterQu(queue1& q, treenode* p) {
if (q.front == (q.rear + 1) % Max)
return false;
q.rear = (q.rear + 1) % Max;
q.data[q.rear] = p;
return true;
}
bool outQu(queue1& q, treenode*& p) {
if (q.front == q.rear)
return false;
q.front = (q.front + 1) % Max;
p = q.data[q.front];
return true;
}
void re_level(tree t) {
stack1 s;
queue1 q;
treenode* p;
if (t != NULL) {
enterQu(q, t);
while (isqueueEmpty(q) == false) {
outQu(q, p);
push(s, p);
if (p->lchild)
enterQu(q, p->lchild);
if (p->rchild)
enterQu(q, p->rchild);
}
while (IsEmpty(s) == false) {
pop(s, p);
printf("%c", p->data);
}
}
}
int main() {
tree t;
creatTree(t);
re_level(t);
return 0;
}
01-02
479
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-27
1270
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-29
1488
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-26
616
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
08-29
1238
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)