【数据结构】二叉树遍历的非递归实现

“ Ctrl AC!一起 AC!”

目录

二叉树结点数据结构:

定义一个顺序栈及其操作:

前序遍历的非递归实现:

中序遍历的非递归实现:

后序遍历的非递归实现:


非递归主要依靠用一个栈记录回溯点,进行回溯。

二叉树结点数据结构:

typedef char datatype;
typedef struct node{
	datatype data;
	struct node *lchild,*rchild;
}bintnode;
typedef bintnode *bintree;
bintree root;

定义一个顺序栈及其操作:

typedef struct stack{
	bintree data[100];
	int tag[100];
	int top;
}seqstack;

void push(seqstack* s,bintree t){
	s->data[s->top]=t;
	s->top++;
} 

bintree pop(seqstack* s){
	if(s->top!=0){
		s->top--;
		return s->data[s->top];
	}
	else return NULL;
}

前序遍历的非递归实现:

void preorder1(bintree t){
	seqstack s;
	s.top=0;
	while(t||s.top!=0){
		if(t){
			printf("%c",t->data);
			push(&s,t);
			t=t->lchild;
		}
		else{
			t=pop(&s);
			t=t->rchild;
		}
	}
}

中序遍历的非递归实现:

void inorder1(bintree t){
	seqstack s;
	s.top=0;
	while(t||s.top!=0){
		if(t){
			push(&s,t);
			t=t->lchild;
		}
		else{
			t=pop(&s);
			printf("%c",t->data);
			t=t->rchild;
		}
	}
}

后序遍历的非递归实现:

void postorder1(bintree t){
	seqstack s;
	s.top=0;
	while(t||s.top!=0){
		if(t){
			s.data[s.top]=t;
			s.tag[s.top]=0;
			s.top++;
			t=t->child;
		}
		else{
			if(s.tag[s.top-1]==1){ //左右都遍历完 
				s.top--;
				t=s.data[s.top];
				printf("%c",t->data);
				t=NULL;
			} 
			else{ //只遍历了左,接下来遍历右边 
				t=s.data[s.top-1];
				s.tag[s.top-1]=1;
				t=t->rchild;
			}
		}
	}
}

感谢阅读!!!

“ Ctrl AC!一起 AC!”

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ctrl AC

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值