如果要对二叉树进行自下而上,自右向左的层次遍历,请给出遍历算法。
解题思路:ggt
1.采用层次遍历,初始化一个空队列和空栈
2.每次出队时将该元素入栈,直至层次遍历结束
3.不断将栈顶元素出栈,同时对其访问,直至栈空
ps:偷懒将层次遍历的序列存入数组中,在将数组中的data值逆序输出,即可得到反向层次遍历的序列
- #include
- #include
- #include
- using namespace std;
-
- //string qx="12400500300";//完全二叉树测试数据
- //string zx="04020501030";
- string qx="123" ;//非完全二叉树测试数据
- string zx="321";
- const int MaxSize=100;
- typedef struct Tree//二叉树结构定义
- {
- int data;
- Tree *left;
- Tree *right;
- } *BiTree;
-
- BiTree build(string qx,string zx)//建树
- {
- if(qx.size()==0)return NULL;
- Tree *root=(Tree *)malloc(sizeof(Tree));
- root->data=qx[0]-'0';
- int pos=zx.find(qx[0]);
- root->left=build(qx.substr(1,pos),zx.substr(0,pos));
- root->right=build(qx.substr(pos+1),zx.substr(pos+1));
- return root;
- }
-
- typedef struct LinkNode//队列结点
- {
- BiTree data;
- LinkNode *next;
- }LinkNode,*Link;
- typedef struct Queue//链队列
- {
- LinkNode *front;
- LinkNode *rear;
- }*queue;
-
- void InitQueue(Queue &Q)
- {
- Q.front=Q.rear=(LinkNode*)malloc(sizeof(LinkNode));
- Q.front->next=NULL;
- }
-
- bool isEmpty(Queue Q)
- {
- if(Q.front==Q.rear) return true;
- else return false;
- }
-
- void EnQueue(Queue &Q,BiTree x)
- {
- LinkNode *p=(LinkNode*)malloc(sizeof(LinkNode));
- p->data=x;
- p->next=Q.rear->next;
- Q.rear->next=p;
- Q.rear=p;
- }
-
- bool DeQueue(Queue &Q,BiTree &x)
- {
- if(Q.front==Q.rear) return false;
- LinkNode *p=Q.front->next;
- x=p->data;
- Q.front->next=p->next;
- if(Q.rear==p) Q.rear=Q.front;
- return true;
- }
-
- void LevelOrder(BiTree T)//层次遍历
- {
- int a[10];
- int i=0;
- BiTree x;
- Queue Q;
- InitQueue(Q);
- BiTree p=T;
- EnQueue(Q,p);
- while(!isEmpty(Q))
- {
- DeQueue(Q,x);
- a[i++]=x->data;//将层次遍历得到的序列存入数组中
- if(x->left!=NULL)
- EnQueue(Q,x->left);
- if(x->right!=NULL)
- EnQueue(Q,x->right);
- }
- for(int j=i-1;j>=0;j--)//将数组中的data值逆序输出
- {
- printf("%d ",a[j]);
- }
- }
-
- int main()
- {
- BiTree T=build(qx,zx);
- LevelOrder(T);
- }