对二叉树执行遍历:奇数层从左到右,偶数层从右到左遍历。用逗号将每个数据元素隔开
思想:
利用层次遍历实现,将每一层元素放到栈内,根据层次来判断是进行逆序输出还是正序输出。
层次遍历确定同一层的结点;用数组来实现队列,front指向队首元素前一个元素,rear指向队尾元素,rear-front指向队尾元素,rear-front表示队列中元素个数(也就是那一层的元素个数)。
代码:
void leftrightlevel(BiTree root){if(root==NULL) return;BiTree stack[MaxSize];//定义栈 int top; BiTree queue[MaxSize];//定义队列 int front=-1,rear=-1;queue[++rear]=root;//根入队int count=0;//用来记录是第几层while(front < rear){//队列不为空count++;//层次+1top=-1;//栈设置为空int sum=rear-front;//队列中元素个数,也就是这一层的元素个数while(sum-- >0) {//遍历这一层的元素个数 BiTree *p=queue[++front];//出队stack[++top]=p;//入栈if(p->lchild!=NULL){queue[++rear]=p->lchild;} if(p->rchild!=NULL){queue[++rear]=p->rchild;}}if(count%2==0){//偶数层,逆序输出 while(top != -1) printf("%d ", stack[top--]->data);}else {//奇数层,正序输出 int index=0;while(index<=top) printf("%d ", stack[index++]->data);}printf(",");} }