非递归遍历二叉树

 二叉树先序、中序遍历。

#include<cstdio>
#include<stack>
using namespace std; 

typedef struct btree{
	char data;
	struct btree *ltree,*rtree;
}tree,*Tree;

//递归先序创建二叉树 
void create(Tree &t)
{
	char c;
	scanf("%c",&c);
	if(c==' ') t=NULL;
	else{
		t=new btree;//t=(Tree)malloc(sizeof(tree)),,,,t=(*btree)malloc(sizeof(btree))
		t->data=c;
		create(t->ltree);
		create(t->rtree);
	}
}

//非递归先序遍历 
void PreOrder(Tree &t)
{
	Tree p;
	stack<Tree>s;
	if(t){
		s.push(t); 
		while(!s.empty()){
			p=s.top();
			s.pop();
			while(p){
				printf("%c\t",p->data);
				if(p->rtree) s.push(p->rtree); //右子树非空进栈 
				p=p->ltree; //沿左子树往下走 
			}
		}
	}
}

//非递归中序遍历
void InOrder(Tree &t)
{
	Tree p;
	stack<Tree>s;
	s.push(t);
	while(!s.empty()){
		while((p=s.top())&&p) s.push(p->ltree); //向左走到尽头,知直到没有左子树 MMMM 
		p=s.top();
		s.pop();//最后一个节点的左子树为空,需要弹出 
		if(!s.empty()){
			p=s.top();
			printf("%c\t",p->data);//取出最后的左子树并访问 
			s.pop();
			s.push(p->rtree);//将最后一个左子树的双亲的右子树入栈,下个循环开始遍历右子树的子树(上面MMM处) 
		}
	}
 } 
 
int main()
{
	Tree t;
	create(t);
	PreOrder(t); 
	printf("\n");
	InOrder(t);
 } 
 
 //输入:ABC  DE G  F   (F后面有三个空格)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值