思路:在层次的遍历的基础上,利用栈,层次遍历每次出队一个结点,则把这个结点放入栈中,这样最后出栈的时候,结点的出栈顺序即为自下而上,从右到左。
样例:
代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<string.h>
#include <stdlib.h>
//二叉树结构
typedef struct bitree {
char data;
struct bitree* lchild, * rchild;
}bitree;
typedef struct{
bitree* data[50];
int front, rear;
}sequeue;//队列
typedef struct {
bitree* data1[50];
int top;
}stack;//栈
//创建二叉树
void create(bitree** t) {
char ch;
scanf("%c", &ch);
if (ch == '#') {
*t = NULL;
}
else {
*t = (bitree*)malloc(sizeof(bitree));
(*t)->data = ch;
create(&((*t)->lchild));
create(&((*t)->rchild));
}
}
void levelorder(bitree** t) {
sequeue s;
stack s1;
s1.top = -1;
s.front = s.rear = 0;
bitree* p = *t; //把根节点赋值给指针p
s.data[(s.rear)++] = p;
while (s.front!=s.rear) {
p = s.data[(s.front)++];
s1.data1[++(s1.top)] = p; //把层次遍历的每个结点一次放入栈中
if (p->lchild != NULL) {
s.data[(s.rear)++] = p->lchild;
}
if (p->rchild != NULL) {
s.data[(s.rear)++] = p->rchild;
}
}
while (s1.top != -1) { //出栈
p = s1.data1[(s1.top)--];
printf("%c ", p->data);
}
}
int main() {
bitree* t = NULL;
create(&t);
levelorder(&t);
return 0;
}
结果: