试给出二叉树的自下而上,从右到左的层次遍历算法。
![](https://img-blog.csdnimg.cn/img_convert/d1c971670af632000cc073d3b83420f6.jpeg)
我本来想用c语言来解决的,结果使用队列和栈的过程中不知道为啥出现错误了,我直接用c++的stack容器和queue容器来代替了。(有大佬能看看我c语言的代码有啥问题嘛。。)
#include<iostream>
#include<bits/stdc++.h>
using namespace std;
typedef struct BiNode {
char data;
struct BiNode* lchild, * rchild;
}BiNode, * BiTree;
//typedef struct stack {
// BiTree data[1024];
// int top;
//}stack;
//typedef struct queue {
// BiTree data[1024];
// int front, rear;
//}queue;
//void initqueue(queue q) {
// q.front = q.rear = 0;
//}
//void EnQueue(queue &q, BiTree t) {
// q.data[q.rear++] = t;
//}
//bool isempty(queue q) {
// if (q.front == q.rear)return true;
// else return false;
//}
//void DeQueue(queue& q, BiTree &p) {
// p = q.data[q.front++];
//}
//void initstack(stack& s) {
// s.top = 0;
//}
//bool isempty(stack s) {
// if (s.top == 0)return true;
// else return false;
//}
//void push(stack& s, BiTree t) {
// if (s.top == 1024)return;
// s.data[s.top++] = t;
//}
//void pop(stack& s, BiTree& t) {
// if (isempty(s))return;
// t = s.data[--s.top];
//}
//void GetTop(stack s, BiTree &p) {
// p = s.data[--s.top];
//}
void create(BiTree& t) {//二叉树先序
char ch;
cin >> ch;
if (ch == '@')t = NULL;
else {
t = new BiNode;
t->data = ch;
create(t->lchild);
create(t->rchild);
}
}
void InvertLevel(BiTree t) {
queue<BiTree>q;
stack<BiTree>s;
BiTree r = NULL;
BiTree p = t;
q.push(p);
while (!empty(q)) {
p = q.front();
q.pop();
s.push(p);
if (p->lchild)q.push(p->lchild);
if (p->rchild)q.push(p->rchild);
}
while (!empty(s)) {
p = s.top();
s.pop();
cout << p->data;
}
}
int main() {
BiTree t;
create(t);//测试数据:abd@@e@@c@@
//abcde
//edcba
InvertLevel(t);
}