二叉树的非递归遍历(先序 后序 中序)

在上一篇中,我们已经说过先序、中序、后序的递归实现
非递归的遍历要怎么实现????
先序和中序则较为简单,

  • 采用栈的结构(先进后出),先序是在入栈时将其数据域读出来,中序则是在出栈是将其数据域读出
  • 注意的是在入栈和出栈的时候要判断栈的情况
//先序遍历二叉树(非递归):采用栈的形式
void PreOrder_1(Node *root) {
	if (root==NULL) {
		return;
	}
	Node *stack[SIZE];
	Node *tmp = root;
	int top = 0;//top代表栈顶
	while (tmp!=NULL||top!=0) {
		while (tmp!=NULL) {
			printf("%d", tmp->data);
			//将指针入栈,判断栈
			if (top<SIZE) {
				stack[top] = tmp;
				top++;
				tmp = tmp->left;
			}
			else {
				return;
			}
		}
		//栈为空
		if (top<=0) {
			return;
		}
		else {
			top--;
			tmp = stack[top];
			tmp = tmp->right;
		}
	}
}


void InOreder_1(Node *root) {
	while (root==NULL) {
		return;
	}
	Node* stack[SIZE];
	Node* tmp = root;
	int top = 0;//代表栈顶
	while (tmp!=NULL||top!=0){
		while (tmp != NULL) {
			if (top<SIZE) {
				stack[top] = tmp;
				tmp = tmp->left;
				top++;
			}
			else {
				return;
			}
		}
		if (top<=0) {
			return;
		}else{
			top--;
			tmp = stack[top];
			printf("%d", tmp->data);
			tmp = tmp->right;
		}

	}
}
  • 后序遍历,是将其左节点和右结点访问之后再访问根节点,因此我们要判断根节点的右结点是否为空,并且是否被访问过,判断是否被访问过,我们用指针来标记访问的结点
//后序遍历二叉树(非递归),相对于前序和中序较为复杂
void PostOrder_1(Node *root) {
	if (root==NULL) {
		return;
	}
	Node *stack[SIZE];
	Node *tmp = root;
	int top = 0;
	Node*re = NULL;
	while (tmp!=NULL||top!=0) {
		while (tmp!=NULL) {
			if (top<SIZE) {
				stack[top] = tmp;
				tmp = tmp->left;
				top++;
			}else {
				return;
			}
		}
		top--;
		tmp = stack[top];
		if (tmp->right&&tmp->right!=re) {
			tmp = tmp->right;
			top++;//将其入栈
		}
		else {
			printf("%d", tmp->data);
			re = tmp;
			tmp = NULL;
		}
	}
}
发布了50 篇原创文章 · 获赞 19 · 访问量 4711

猜你喜欢

转载自blog.csdn.net/qq_44723296/article/details/103349553
今日推荐