二叉树:自下而上,从左到右的层次遍历
利用栈先进后出的特性,将出队元素依次进栈,然后依次出栈即可完成。
#include <stdio.h> #include <stdlib.h> #define MaxSize 100 //二叉树的结点类型 typedef struct Node{ int data; struct Node *lchild,*rchild; }TreeNode,*Tree; //队列的结点类型 typedef struct{ TreeNode* data[MaxSize]; int front,rear; }Queue; //栈的结点类型 typedef struct{ TreeNode* data[MaxSize]; int top; }Stack; //初始化队列 void InitQueue(Queue &Q) { Q.front=Q.rear=0; } //队列判空 bool isEmpty(Queue Q) { if(Q.front==Q.rear) return true; return false; } //队列判满 bool isFull(Queue Q) { if((Q.rear+1)%MaxSize==Q.front) return true; return false; } //入队 bool EnQueue(Queue &Q,TreeNode *p) { if(isFull(Q)) return false; Q.data[Q.rear]=p; Q.rear=(Q.rear+1)%MaxSize; return true; } //出队 bool DeQueue(Queue &Q,TreeNode* &p) { if(isEmpty(Q)) return false; p=Q.data[Q.front]; Q.front=(Q.front+1)%MaxSize; return true; } //初始化栈 void InitStack(Stack &S) { S.top=-1; }
//栈判空 bool StackIsEmpty(Stack S) { if(S.top==-1) return true; return false; } //进栈 bool Push(Stack &S,TreeNode *p) { if(S.top==MaxSize-1) return false; S.data[++S.top]=p; return true; } //出栈 bool Pop(Stack &S,TreeNode* &p) { if(S.top==-1) return false; p=S.data[S.top--]; return true; } //获取栈顶元素 bool GetTop(Stack S,TreeNode* &p) { if(S.top==-1) return false; p=S.data[S.top]; return true; } //先序创建二叉树 void CreateTree(Tree &T) { int x; scanf("%d",&x); if(x==-1) { T=NULL; return; } else { T=(Tree)malloc(sizeof(TreeNode)); T->data=x; printf("输入%d的左结点:",x); CreateTree(T->lchild); printf("输入%d的右结点:",x); CreateTree(T->rchild); } } //自下而上,从右到左的层次遍历 void LevelOrder(Tree T) { Stack S; InitStack(S); Queue Q; InitQueue(Q); TreeNode *p=T; EnQueue(Q,p); while(!isEmpty(Q)) { DeQueue(Q,p); Push(S,p); if(p->lchild!=NULL) EnQueue(Q,p->lchild); if(p->rchild!=NULL) EnQueue(Q,p->rchild); } while(!StackIsEmpty(S)) { Pop(S,p); printf("%d ",p->data); } } int main() { Tree T; CreateTree(T); LevelOrder(T); return 0; }