/**
*2018.09.14 17:37
*二叉树的遍历 not recursion
*先根,中根,后根,层次
*/
#include<stdio.h>
#define MAX 100
typedef struct BTNode {
int e;
struct BTNode *rchild, *lchild;
}BTNode;
void preOrder(BTNode *p);
void inOrder(BTNode *p);
void postOrder(BTNode *p);
void levelTraverse(BTNode *p);
int main(void) {
system("COLOR fc");
putchar('\n');
system("pause");
return 0;
}
void preOrder(BTNode *p) {
if (p != NULL) {
BTNode *stack[MAX];
int top = -1;
BTNode *c;
stack[++top] = p;
while (top != -1) {
c = stack[top--];
printf("5%d",c->e);
if (c->rchild != NULL)
stack[++top] = c->rchild;
if (c->lchild != NULL)
stack[++top] = c->lchild;
}
}
}
void inOrder(BTNode *p) {
if (p != NULL) {
int top = -1;
BTNode *stack[MAX];
BTNode *c = p;
while (top != -1 || c != NULL) {
while (c != NULL) {
stack[++top] = c;
c = c->lchild;
}
//这里的if判断我觉得没有必要,但书上有
//if (top != -1) {
c = stack[top--];
printf("%5d", c->e);
c = c->rchild;
//}
}
}
}
void postOrder(BTNode *p) {
if (p != NULL) {
BTNode *c, *stack[MAX], *temp_stack[MAX];
int top, temp_top;
top = temp_top = -1;
temp_stack[++temp_top] = p;
while (-1 != temp_top) {
c = temp_stack[temp_top--];
stack[++top] = c;
if (c->lchild != NULL)
temp_stack[++temp_top] = c->lchild;
if (c->rchild != NULL)
temp_stack[++temp_top] = c->rchild;
}
while (-1 != top)
printf("%5d ", stack[top--]->e);
}
}
//运用到了循环队列
void levelTraverse(BTNode *p) {
if (NULL != p) {
BTNode *queue[MAX], *c;
int front, rear;
front = rear = 0;
rear = (rear + 1) % MAX;
queue[rear] = p;
while (front != rear) {
front = (front + 1) % MAX;
c = queue[front];
printf("%5d ", c->e);
if (NULL != c->lchild) {
rear = (rear + 1) % MAX;
queue[rear] = c->lchild;
}
if (NULL != c->rchild) {
rear = (rear + 1) % MAX;
queue[rear] = c->rchild;
}
}
}
二叉树的非递归形式的前、中、后遍历以及层次遍历
最新推荐文章于 2022-11-21 10:37:50 发布