二叉树的非递归形式的前、中、后遍历以及层次遍历

/**
*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;
			}		
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值