数据结构-二叉树遍历非递归
前序遍历
void preOrder(BiTree bt){
if (bt!=NULL){
BiTree Stack[maxSize];
int top = -1;
Stack[++top]=bt;
BiTree p;
while (top!=1){
p=Stack[top--];
visit(p);
if (p->r!=NULL)
Stack[++top]=p->r;
if (p->l!=NULL)
Stack[++top]=p->l;
}
}
}
后序遍历
void postOrder(BiTree bt){
if (bt!=NULL){
BiTree Stack[maxSize];
int top1 = -1;
int top2 = -1;
Stack1[++top1]=bt;
Stack2[++top1]=bt;
BiTree p;
while (top1!=1){
p=Stack[top1--];
Stack2[++top2]=p;
if (p->l!=NULL)
Stack[++top1]=p->l;
if (p->r!=NULL)
Stack[++top1]=p->r;
}
while(top1!=1){
p=Stack2[top2--];
visit(p);
}
}
}
中续遍历
void inOrder(BiTree bt) {
if (bt!=NULL) {
BiTree Stack[maxSize];
int top = -1;
BiTree p = bt;
while (top != -1 || p != NULL) {
while (p != NULL) {
Stack[++top] = p;
p = p->l;
}
if (top != 1) {
p = Stack[top--];
visit(p);
if (p->r != NULL)
Stack[++top] = p->r;
}
}
}
}
层续遍历
void levelOrder(BiTree bt){
if (bt!=NULL){
BiTree Queue[maxSize];
BiTree p;
int front;
int rear;
front = rear = 0;
rear = rear + 1 % maxSize;
Queue[rear] = bt;
while (front != rear){
front = front + 1 % maxSize;
p = Queue[front];
visit(p);
if(p->l != NULL){
rear = rear + 1 % maxSize;
Queue[rear] = bt;
}
if(p->r != NULL){
rear = rear + 1 % maxSize;
Queue[rear] = bt;
}
}
}
}
浙公网安备 33010602011771号